<!doctype html>



  


<html class="theme-next mist use-motion">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="baidu-site-verification" content="zD47G9xe42" />


<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />












  
  
  <link href="/vendors/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/vendors/font-awesome/css/font-awesome.min.css?v=4.4.0" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.0.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="uiste个人博客网站,uiste,uiste博客,PHP,运维,Hexo,技术博客" />





  <link rel="alternate" href="/atom.xml" title="uiste" type="application/atom+xml" />




  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.0.1" />






<meta name="description" content="Stay Hungry，Stay Foolish">
<meta property="og:type" content="website">
<meta property="og:title" content="uiste">
<meta property="og:url" content="http://blog.uiste.com/page/9/index.html">
<meta property="og:site_name" content="uiste">
<meta property="og:description" content="Stay Hungry，Stay Foolish">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="uiste">
<meta name="twitter:description" content="Stay Hungry，Stay Foolish">



<script type="text/javascript" id="hexo.configuration">
  var NexT = window.NexT || {};
  var CONFIG = {
    scheme: 'Mist',
    sidebar: {"position":"left","display":"post"},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: 0,
      author: '博主'
    }
  };
</script>




  <link rel="canonical" href="http://blog.uiste.com/page/9/"/>

  <title>
 
  uiste - Stay Hungry，Stay Foolish 

</title>
</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  



  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?b58b87af012832b8ae35e33bb45b44fa";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>








  
  
    
  

  <div class="container one-collumn sidebar-position-left 
   page-home 
 ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-meta ">
  

  <div class="custom-logo-site-title">
    <a href="/"  class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <span class="site-title">uiste</span>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>
  <p class="site-subtitle">uiste个人博客</p>
</div>

<div class="site-nav-toggle">
  <button>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
    <span class="btn-bar"></span>
  </button>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      

            <li class="menu-item menu-item-search"> <a title="把这个链接拖到你的Chrome收藏夹工具栏中" href='javascript:(function() {
    function c() {
        var e = document.createElement("link");
        e.setAttribute("type", "text/css");
        e.setAttribute("rel", "stylesheet");
        e.setAttribute("href", f);
        e.setAttribute("class", l);
        document.body.appendChild(e)
    }
 
    function h() {
        var e = document.getElementsByClassName(l);
        for (var t = 0; t < e.length; t++) {
            document.body.removeChild(e[t])
        }
    }
 
    function p() {
        var e = document.createElement("div");
        e.setAttribute("class", a);
        document.body.appendChild(e);
        setTimeout(function() {
            document.body.removeChild(e)
        }, 100)
    }
 
    function d(e) {
        return {
            height : e.offsetHeight,
            width : e.offsetWidth
        }
    }
 
    function v(i) {
        var s = d(i);
        return s.height > e && s.height < n && s.width > t && s.width < r
    }
 
    function m(e) {
        var t = e;
        var n = 0;
        while (!!t) {
            n += t.offsetTop;
            t = t.offsetParent
        }
        return n
    }
 
    function g() {
        var e = document.documentElement;
        if (!!window.innerWidth) {
            return window.innerHeight
        } else if (e && !isNaN(e.clientHeight)) {
            return e.clientHeight
        }
        return 0
    }
 
    function y() {
        if (window.pageYOffset) {
            return window.pageYOffset
        }
        return Math.max(document.documentElement.scrollTop, document.body.scrollTop)
    }
 
    function E(e) {
        var t = m(e);
        return t >= w && t <= b + w
    }
 
    function S() {
        var e = document.createElement("audio");
        e.setAttribute("class", l);
        e.src = i;
        e.loop = false;
        e.addEventListener("canplay", function() {
            setTimeout(function() {
                x(k)
            }, 500);
            setTimeout(function() {
                N();
                p();
                for (var e = 0; e < O.length; e++) {
                    T(O[e])
                }
            }, 15500)
        }, true);
        e.addEventListener("ended", function() {
            N();
            h()
        }, true);
        e.innerHTML = " <p>If you are reading this, it is because your browser does not support the audio element. We recommend that you get a new browser.</p> <p>";
        document.body.appendChild(e);
        e.play()
    }
 
    function x(e) {
        e.className += " " + s + " " + o
    }
 
    function T(e) {
        e.className += " " + s + " " + u[Math.floor(Math.random() * u.length)]
    }
 
    function N() {
        var e = document.getElementsByClassName(s);
        var t = new RegExp("\\b" + s + "\\b");
        for (var n = 0; n < e.length; ) {
            e[n].className = e[n].className.replace(t, "")
        }
    }
 
    var e = 30;
    var t = 30;
    var n = 350;
    var r = 350;
    var i = "//s3.amazonaws.com/moovweb-marketing/playground/harlem-shake.mp3";
    var s = "mw-harlem_shake_me";
    var o = "im_first";
    var u = ["im_drunk", "im_baked", "im_trippin", "im_blown"];
    var a = "mw-strobe_light";
    var f = "//s3.amazonaws.com/moovweb-marketing/playground/harlem-shake-style.css";
    var l = "mw_added_css";
    var b = g();
    var w = y();
    var C = document.getElementsByTagName("*");
    var k = null;
    for (var L = 0; L < C.length; L++) {
        var A = C[L];
        if (v(A)) {
            if (E(A)) {
                k = A;
                break
            }
        }
    }
    if (A === null) {
        console.warn("Could not find a node of the right size. Please try a different page.");
        return
    }
    c();
    S();
    var O = [];
    for (var L = 0; L < C.length; L++) {
        var A = C[L];
        if (v(A)) {
            O.push(A)
        }
    }
})()    '>High</a> </li>

    </ul>
  

 
    <div class="site-search">
      
  <div class="popup">
 <span class="search-icon fa fa-search"></span>
 <input type="text" id="local-search-input">
 <div id="local-search-result"></div>
 <span class="popup-btn-close">close</span>
</div>


    </div>
   
</nav>

 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            
  <section id="posts" class="posts-expand">
    
      

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                
                <a class="post-title-link" href="/20160830-1.html" itemprop="url">
                  Day8-MySQL 数据类型、列属性、数据完整性
                </a>
              
            
          </h1>
        

        <div class="post-meta">
        
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">发表于</span>
            <time itemprop="dateCreated" datetime="2016-08-30T17:18:51+08:00" content="2016-08-30">
              2016-08-30
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/MySQL/" itemprop="url" rel="index">
                    <span itemprop="name">MySQL</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/20160830-1.html#comments" itemprop="discussionUrl">
                  <span class="post-comments-count ds-thread-count" data-thread-key="20160830-1.html" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          

          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <h3 id="数据类型"><a href="#数据类型" class="headerlink" title="数据类型"></a>数据类型</h3><h4 id="数据类型——值类型"><a href="#数据类型——值类型" class="headerlink" title="数据类型——值类型"></a>数据类型——值类型</h4><h5 id="整型"><a href="#整型" class="headerlink" title="整型"></a>整型</h5><table>
<thead>
<tr>
<th>整型</th>
<th style="text-align:center">占用字节</th>
<th style="text-align:center">范围</th>
<th style="text-align:center">范围</th>
</tr>
</thead>
<tbody>
<tr>
<td>tinyint</td>
<td style="text-align:center">1</td>
<td style="text-align:center">-2^7~2^7-1</td>
<td style="text-align:center">-128~127</td>
</tr>
<tr>
<td>smallint</td>
<td style="text-align:center">2</td>
<td style="text-align:center">-2^15~2^15-1</td>
<td style="text-align:center">-32768~32767</td>
</tr>
<tr>
<td>mediumint</td>
<td style="text-align:center">3</td>
<td style="text-align:center">-2^23~2^23-1</td>
<td style="text-align:center">-8388608~8388607</td>
</tr>
<tr>
<td>int</td>
<td style="text-align:center">4</td>
<td style="text-align:center">-2^31~2^31-1</td>
<td style="text-align:center">-2147483648~2147483647</td>
</tr>
<tr>
<td>bigint</td>
<td style="text-align:center">8</td>
<td style="text-align:center">-2^63~2^63-1</td>
<td style="text-align:center">-</td>
</tr>
</tbody>
</table>
<blockquote>
<p>一个字节=8位，8位就是8个二进制数</p>
</blockquote>
<ul>
<li>整型支持显示宽度：最小的显示位数，比如int(5)，如果数值的位数小于5位，前面加上前导0。比如输入12，显示00012；大于5位就不添加前导0</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div></pre></td><td class="code"><pre><div class="line">mysql&gt; describe student;</div><div class="line">+-------+--------------------------+------+-----+---------+----------------+</div><div class="line">| Field | Type                     | Null | Key | Default | Extra          |</div><div class="line">+-------+--------------------------+------+-----+---------+----------------+</div><div class="line">| id    | int(11)                  | NO   | PRI | NULL    | auto_increment |</div><div class="line">| name  | char(1)                  | YES  |     | NULL    |                |</div><div class="line">| num   | int(8) unsigned zerofill | YES  |     | NULL    |                |</div><div class="line">+-------+--------------------------+------+-----+---------+----------------+</div><div class="line">3 rows in set (0.01 sec)</div><div class="line"></div><div class="line">mysql&gt; select * from student;</div><div class="line">+----+------+------------+</div><div class="line">| id | name | num        |</div><div class="line">+----+------+------------+</div><div class="line">|  1 | a    |   00002485 |</div><div class="line">|  2 | b    |   03678928 |</div><div class="line">|  3 | c    | 1234567890 |</div><div class="line">+----+------+------------+</div><div class="line">3 rows in set (0.00 sec)</div></pre></td></tr></table></figure>
<blockquote>
<p>脚下留心：必须结合zerofill才起作用<br>显示宽度不决定显示范围，只是在数值不够指定位数时用0做前导</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div></pre></td><td class="code"><pre><div class="line">mysql&gt; alter table student add num2 tinyint;</div><div class="line">Query OK, 0 rows affected (0.05 sec)</div><div class="line">Records: 0  Duplicates: 0  Warnings: 0</div><div class="line"></div><div class="line">mysql&gt; insert into student values (null,&apos;d&apos;,&apos;1&apos;,128);</div><div class="line">Query OK, 1 row affected, 1 warning (0.01 sec)</div><div class="line"></div><div class="line">mysql&gt; select * from student;</div><div class="line">+----+------+------------+------+</div><div class="line">| id | name | num        | num2 |</div><div class="line">+----+------+------------+------+</div><div class="line">|  1 | a    |   00002485 | NULL |</div><div class="line">|  2 | b    |   03678928 | NULL |</div><div class="line">|  3 | c    | 1234567890 | NULL |</div><div class="line">|  4 | d    |   00000001 |  127 |</div><div class="line">+----+------+------------+------+</div><div class="line">4 rows in set (0.00 sec)</div></pre></td></tr></table></figure>
<blockquote>
<p>超出最大范围会有警告提示，同时值保存最大范围值</p>
</blockquote>
<ul>
<li>无符号整数（unsigned）：无符号数没有负数，正数部分是有符号的两倍</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line">mysql&gt; insert into student values (null,666);</div><div class="line">Query OK, 1 row affected, 1 warning (0.01 sec)</div><div class="line"></div><div class="line">mysql&gt; select * from student;</div><div class="line">+----+------+</div><div class="line">| id | num  |</div><div class="line">+----+------+</div><div class="line">|  7 |  255 |</div><div class="line">+----+------+</div><div class="line">1 row in set (0.00 sec)</div></pre></td></tr></table></figure>
<h5 id="浮点型（保存近似值小数）"><a href="#浮点型（保存近似值小数）" class="headerlink" title="浮点型（保存近似值小数）"></a>浮点型（保存近似值小数）</h5><table>
<thead>
<tr>
<th>浮点型</th>
<th style="text-align:center">占用字节</th>
<th style="text-align:center">范围</th>
</tr>
</thead>
<tbody>
<tr>
<td>float（单精度）</td>
<td style="text-align:center">4</td>
<td style="text-align:center">-3.4E+38~3.4E+38</td>
</tr>
<tr>
<td>double（双精度）</td>
<td style="text-align:center">8</td>
<td style="text-align:center">-1.8E+308~1.8E+308</td>
</tr>
</tbody>
</table>
<ul>
<li>浮点数声明:  float(M,D)   double(M,D)<br>M：总位数<br>D：小数位数</li>
</ul>
<blockquote>
<p>浮点数也是支持显示宽度和无符号数</p>
</blockquote>
<ul>
<li>浮点数支持科学计数法<br><code>insert into uiste values (5E2,4E-1);</code></li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line">mysql&gt; insert into student values (null,5E2,4E-1);</div><div class="line">Query OK, 1 row affected (0.00 sec)</div><div class="line"></div><div class="line">mysql&gt; select * from student;</div><div class="line">+----+--------------+------+</div><div class="line">| id | num1         | num2 |</div><div class="line">+----+--------------+------+</div><div class="line">|  7 |         NULL | NULL |</div><div class="line">|  8 | 000000000500 | 00.4 |</div><div class="line">+----+--------------+------+</div><div class="line">2 rows in set (0.00 sec)</div></pre></td></tr></table></figure>
<ul>
<li>浮点的精度可能会丢失【指的是小数】<br><code>insert into uiste values (99.999999999);</code></li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line">mysql&gt; insert into student values (null,9.99999999999999,1.1111111111111);</div><div class="line">Query OK, 1 row affected (0.01 sec)</div><div class="line"></div><div class="line">mysql&gt; select * from student;</div><div class="line">+----+--------------+------+</div><div class="line">| id | num1         | num2 |</div><div class="line">+----+--------------+------+</div><div class="line">|  7 |         NULL | NULL |</div><div class="line">|  8 | 000000000500 | 00.4 |</div><div class="line">|  9 | 000000000010 | 01.1 |</div><div class="line">+----+--------------+------+</div><div class="line">3 rows in set (0.00 sec)</div></pre></td></tr></table></figure>
<blockquote>
<p>小数部分如果超过D的限制会四舍五入，整数部分不能超过M-D的限制</p>
</blockquote>
<ul>
<li>定点数<br>语法：decimal(M,D)</li>
</ul>
<blockquote>
<p>定点数是变长的，大致每9个数字用4个字节来存储。定点数之所以能保存精确的小数，因为整数和小数是分开存储的。占用的资源比浮点数要多。<br>定点数和浮点数都支持显示宽度和无符号数</p>
</blockquote>
<h4 id="数据类型——字符型"><a href="#数据类型——字符型" class="headerlink" title="数据类型——字符型"></a>数据类型——字符型</h4><table>
<thead>
<tr>
<th>数据类型</th>
<th style="text-align:center">描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>char(L)</td>
<td style="text-align:center">定长</td>
</tr>
<tr>
<td>varchar(L)</td>
<td style="text-align:center">变长</td>
</tr>
<tr>
<td>tinytext</td>
<td style="text-align:center">2^8-1=255</td>
</tr>
<tr>
<td>text</td>
<td style="text-align:center">2^16-1=65535</td>
</tr>
<tr>
<td>mediumtext</td>
<td style="text-align:center">2^24-1</td>
</tr>
<tr>
<td>longtext</td>
<td style="text-align:center">2^32-1</td>
</tr>
</tbody>
</table>
<blockquote>
<p>char(10)和varchar(10)的区别？<br>答：相同点：它们最多只能保存10个字符；<br>不同点：char不回收富余的字符，varchar会回收富余的字符。<br>char效率高，浪费空间，varchar节省空间，效率比char低。</p>
<p>char的最大长度是255。varchar理论长度是65535字节,实际根本达不到。具体长度与字符编码有关</p>
<p>大块文本（text）不计算在总长度中,一个大块文本只占用10个字节来保存文本的地址。</p>
</blockquote>
<h4 id="数据类型——枚举（enum）"><a href="#数据类型——枚举（enum）" class="headerlink" title="数据类型——枚举（enum）"></a>数据类型——枚举（enum）</h4><p>从集合中选择一个数据（单选）</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div></pre></td><td class="code"><pre><div class="line">mysql&gt; create database uiste charset=utf8;</div><div class="line">Query OK, 1 row affected (0.01 sec)</div><div class="line"></div><div class="line">mysql&gt; create table student(</div><div class="line">    -&gt; name varchar(20),</div><div class="line">    -&gt; sex enum(&apos;男&apos;,&apos;女&apos;,&apos;保密&apos;)</div><div class="line">    -&gt; )charset=utf8;</div><div class="line">Query OK, 0 rows affected (0.02 sec)</div><div class="line"></div><div class="line">mysql&gt; insert into student values (&apos;杜敏&apos;,&apos;男&apos;);</div><div class="line">Query OK, 1 row affected (0.00 sec)</div><div class="line"></div><div class="line">mysql&gt; insert into student values (&apos;钟程程&apos;,&apos;男或女&apos;);</div><div class="line">Query OK, 1 row affected, 1 warning (0.01 sec)</div><div class="line"></div><div class="line">mysql&gt; select * from student;</div><div class="line">+-----------+------+</div><div class="line">| name      | sex  |</div><div class="line">+-----------+------+</div><div class="line">| 杜敏      | 男   |</div><div class="line">| 钟程程    |      |</div><div class="line">+-----------+------+</div><div class="line">2 rows in set (0.00 sec)</div></pre></td></tr></table></figure>
<blockquote>
<p>使用枚举进行数据选择的时候，没有屏蔽错误信息只是提示了警告信息</p>
<p>MySQL的枚举类型是通过整数来管理的，第一个值是1，第二个值是2，以此类推<br>既然枚举在数据库内部存储的是整数，那么可以直接插入数字</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div></pre></td><td class="code"><pre><div class="line">mysql&gt; select sex+0 from student;</div><div class="line">+-------+</div><div class="line">| sex+0 |</div><div class="line">+-------+</div><div class="line">|     1 |</div><div class="line">|     0 |</div><div class="line">+-------+</div><div class="line">2 rows in set (0.01 sec)</div><div class="line"></div><div class="line">mysql&gt; insert into student values (&apos;赵哥&apos;,2);</div><div class="line">Query OK, 1 row affected (0.01 sec)</div><div class="line"></div><div class="line">mysql&gt; select * from student;</div><div class="line">+-----------+------+</div><div class="line">| name      | sex  |</div><div class="line">+-----------+------+</div><div class="line">| 杜敏      | 男   |</div><div class="line">| 钟程程    |      |</div><div class="line">| 赵哥      | 女   |</div><div class="line">+-----------+------+</div><div class="line">3 rows in set (0.00 sec)</div></pre></td></tr></table></figure>
<p><strong>枚举的优点：</strong><br>1、    运行速度快（数字比字符串运算速度快）<br>2、    限制数据<br>3、    节省空间</p>
<blockquote>
<p>已知枚举占用2个字节，请问最多有多少个枚举值？<br>答：2个字节=16位，可以保存216个数字（0-65535），枚举是从1开始，所以枚举最多可以有65535个枚举值</p>
</blockquote>
<h4 id="数据类型——集合（set"><a href="#数据类型——集合（set" class="headerlink" title="数据类型——集合（set)"></a>数据类型——集合（set)</h4><p>从集合中选择一些数据（多选）</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">mysql&gt; create table student(</div><div class="line">    -&gt; name char,</div><div class="line">    -&gt; hobby set(&apos;看书&apos;,&apos;玩游戏&apos;,&apos;敲代码&apos;,&apos;看电视&apos;)</div><div class="line">    -&gt; )charset=utf8;</div><div class="line">Query OK, 0 rows affected (0.03 sec)</div></pre></td></tr></table></figure>
<p>插入集合的值</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div></pre></td><td class="code"><pre><div class="line">mysql&gt; insert into student values (&apos;杜敏&apos;,&apos;玩游戏&apos;);</div><div class="line">Query OK, 1 row affected, 1 warning (0.01 sec)</div><div class="line">mysql&gt; insert into student values (&apos;小兰&apos;,&apos;看书,敲代码&apos;);</div><div class="line">Query OK, 1 row affected, 1 warning (0.01 sec)</div><div class="line">mysql&gt; insert into student values (&apos;兰&apos;,&apos;敲代码,看书&apos;);</div><div class="line">Query OK, 1 row affected (0.01 sec)</div><div class="line"></div><div class="line">mysql&gt; select * from student;</div><div class="line">+------+------------------+</div><div class="line">| name | hobby            |</div><div class="line">+------+------------------+</div><div class="line">| 杜   | 玩游戏           |</div><div class="line">| 小   | 看书,敲代码      |</div><div class="line">| 兰   | 看书,敲代码      |</div><div class="line">+------+------------------+</div><div class="line">3 rows in set (0.00 sec)</div></pre></td></tr></table></figure>
<blockquote>
<p>插入的顺序不一样，但是显示的顺序是一样的</p>
<p>集合和枚举一样，每个集合的元素都分配一个固定的值，分配的方式从左往右按2的0、1、2、…次方</p>
</blockquote>
<p>如果是多选，他们的关系是按位或<br>按位与：相同的位上都是1，结果才为1，只要有一个为0，结果为0。<br>按位或：相同的位上只要有一个为1结果就是1。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line">mysql&gt; select hobby+0 from student;</div><div class="line">+---------+</div><div class="line">| hobby+0 |</div><div class="line">+---------+</div><div class="line">|       2 |</div><div class="line">|       5 |</div><div class="line">|       5 |</div><div class="line">+---------+</div><div class="line">3 rows in set (0.01 sec)</div></pre></td></tr></table></figure>
<blockquote>
<p>思考：已知集合占用8个字节，最多可以表示几个选项？<br>答：8个字节=64位，一个位表示1个选项，最多可以表示64个选项。</p>
</blockquote>
<h4 id="数据类型——日期类型"><a href="#数据类型——日期类型" class="headerlink" title="数据类型——日期类型"></a>数据类型——日期类型</h4><table>
<thead>
<tr>
<th>数据类型</th>
<th style="text-align:center">描述</th>
</tr>
</thead>
<tbody>
<tr>
<td>datetime</td>
<td style="text-align:center">日期时间，占用8个字节</td>
</tr>
<tr>
<td>date</td>
<td style="text-align:center">日期</td>
</tr>
<tr>
<td>time</td>
<td style="text-align:center">时间</td>
</tr>
<tr>
<td>timestamp</td>
<td style="text-align:center">时间戳   占用4个字节</td>
</tr>
<tr>
<td>year</td>
<td style="text-align:center">年份   占用1个字节</td>
</tr>
</tbody>
</table>
<ul>
<li>datetime    格式：年-月-日 小时:分钟:秒</li>
</ul>
<p>测试</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">mysql&gt; insert into test10 values (&apos;2016-6-24 15:15:15&apos;);	--正确</div><div class="line">mysql&gt; insert into test10 values (&apos;100-6-24 15:15:15&apos;);		--正确</div><div class="line">mysql&gt; insert into test10 values (&apos;9999-6-24 15:15:15&apos;);	--正确</div><div class="line">mysql&gt; insert into test10 values (&apos;10000-6-24 15:15:15&apos;);	--错误</div></pre></td></tr></table></figure>
<blockquote>
<p>datetime保存范围是：1~9999年</p>
</blockquote>
<ul>
<li>timestamp：时间戳</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">mysql&gt; insert into test11 values (&apos;2016-6-24 15:15:15&apos;);	--正确的</div><div class="line">mysql&gt; insert into test11 values (&apos;1969-12-31 23:59:59&apos;);	--超过范围</div><div class="line">mysql&gt; insert into test11 values (&apos;2038-01-19 11:14:08&apos;);	--超出范围</div><div class="line">mysql&gt; insert into test11 values (&apos;2038-01-19 11:14:07&apos;);	--正确</div></pre></td></tr></table></figure>
<blockquote>
<p>datetime类型timestamp类型在表现上是一样的。他们的区别：<br>datetime是从1到9999，而timestamp从1970年~2038年，2038年01月19日11:14:07秒以后就超出timestamp范围了。</p>
</blockquote>
<ul>
<li><p>year<br>因为只占用1个字节，最多只能表示255个年份，范围是1901-2155之间的年份</p>
</li>
<li><p>time<br>表示时间或时间间隔，范围是-838:59:59~838:59:59</p>
</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">mysql&gt; insert into test13 values (12:12:12);	--正确</div><div class="line">mysql&gt; insert into test13 values (&apos;212:12:12&apos;);	--正确</div><div class="line">mysql&gt; insert into test13 values (&apos;-838:59:59&apos;);--正确</div><div class="line">mysql&gt; insert into test13 values (&apos;838:59:59&apos;);	--正确</div><div class="line">mysql&gt; insert into test13 values (&apos;839:00:00&apos;);	--错误</div></pre></td></tr></table></figure>
<blockquote>
<p>time支持以天的方式插入</p>
</blockquote>
<p><code>insert into student values (&#39;10 12:12:12&#39;);</code></p>
<h4 id="数据类型——boolean"><a href="#数据类型——boolean" class="headerlink" title="数据类型——boolean"></a>数据类型——boolean</h4><p>MySQL不支持boolean类型，true和false在数据库中对应1和0。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line">mysql&gt; create table test1(</div><div class="line">    -&gt; `field` boolean</div><div class="line">    -&gt; )charset=utf8;</div><div class="line">Query OK, 0 rows affected (0.03 sec)</div><div class="line"></div><div class="line">mysql&gt; describe test1;</div><div class="line">+-------+------------+------+-----+---------+-------+</div><div class="line">| Field | Type       | Null | Key | Default | Extra |</div><div class="line">+-------+------------+------+-----+---------+-------+</div><div class="line">| field | tinyint(1) | YES  |     | NULL    |       |</div><div class="line">+-------+------------+------+-----+---------+-------+</div><div class="line">1 row in set (0.01 sec)</div></pre></td></tr></table></figure>
<h4 id="创建数据表的数据类型"><a href="#创建数据表的数据类型" class="headerlink" title="创建数据表的数据类型"></a>创建数据表的数据类型</h4><blockquote>
<p>手机号码一般使用什么数据类型存储?            char<br>性别一般使用什么数据类型存储?                char    enum<br>年龄信息一般使用什么数据类型存储?            tinyint<br>照片信息一般使用什么数据类型存储?            binary(二进制)<br>薪水一般使用什么数据类型存储?                decimal</p>
</blockquote>
<p><strong>一个字段到底选数字还是字符，取决于有没有计算的可能，如果没有计算的可能即使是数字也要用字符类型，比如手机号、QQ号，…</strong></p>
<h3 id="列属性-是否为空-null-not-null"><a href="#列属性-是否为空-null-not-null" class="headerlink" title="列属性-是否为空(null | not null)"></a>列属性-是否为空(null | not null)</h3><p>null：可以为空<br>not null：不可以为空</p>
<h4 id="列属性——默认值（default）"><a href="#列属性——默认值（default）" class="headerlink" title="列属性——默认值（default）"></a>列属性——默认值（default）</h4><blockquote>
<p>如果一个字段没有插入值，可以默认插入一个指定的值<br>没有插入的字段插入默认值<br>default关键字用来插入默认值</p>
</blockquote>
<h4 id="列属性——自动增长（auto-increment）"><a href="#列属性——自动增长（auto-increment）" class="headerlink" title="列属性——自动增长（auto_increment）"></a>列属性——自动增长（auto_increment）</h4><p>字段的值从1开始，每次递增1，特点就在字段中的数据不可能重复，适合为记录生成唯一的id</p>
<blockquote>
<p>在MySQL中，auto_increment必须是主键。但是主键不一定是自动增长的</p>
</blockquote>
<p><strong>既然从1开始，每次递增1，所以一般自动增长都是无符号整数</strong></p>
<blockquote>
<p>如果要给自动增长列插入数据，使用null关键字。<br>自动增长列上的数据被删除，默认情况下此记录的编号不再使用。</p>
<p>思考题：在一个自动增长列上，插入三行，删除两行，插入三行，删除两行，插入三行，删除两行，再插入一个记录编号是多少？<br>答：编号从10开始。删除记录与自动增长的编号没有关系</p>
</blockquote>
<h4 id="列属性——主键（primary-key）"><a href="#列属性——主键（primary-key）" class="headerlink" title="列属性——主键（primary key）"></a>列属性——主键（primary key）</h4><p>主键：唯一标识表中记录的一个或一组列<br>主键的特点：不能重复，不能为空<br>一个表只能有一个主键，主键可以有多个字段组成</p>
<p>主键的作用：</p>
<ul>
<li>保证数据完整性</li>
<li>加快查询速度</li>
</ul>
<h5 id="添加主键：方法一【创建表的时候添加主键】"><a href="#添加主键：方法一【创建表的时候添加主键】" class="headerlink" title="添加主键：方法一【创建表的时候添加主键】"></a>添加主键：方法一【创建表的时候添加主键】</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">mysql&gt; create table stu(</div><div class="line">    -&gt; id int primary key,</div><div class="line">    -&gt; name varchar(20)</div><div class="line">    -&gt; );</div><div class="line">Query OK, 0 rows affected (0.00 sec)</div></pre></td></tr></table></figure>
<h5 id="添加主键：方法二【创建表的时候添加主键】"><a href="#添加主键：方法二【创建表的时候添加主键】" class="headerlink" title="添加主键：方法二【创建表的时候添加主键】"></a>添加主键：方法二【创建表的时候添加主键】</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">mysql&gt; create table stu(</div><div class="line">    -&gt; id int,</div><div class="line">    -&gt; name varchar(20),</div><div class="line">    -&gt; primary key(id)</div><div class="line">    -&gt; );</div></pre></td></tr></table></figure>
<h5 id="添加主键：方法三【更改表的时候添加主键】"><a href="#添加主键：方法三【更改表的时候添加主键】" class="headerlink" title="添加主键：方法三【更改表的时候添加主键】"></a>添加主键：方法三【更改表的时候添加主键】</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line">mysql&gt; create table stu(</div><div class="line">    -&gt; id int,</div><div class="line">    -&gt; name varchar(20)</div><div class="line">    -&gt; );</div><div class="line">Query OK, 0 rows affected (0.00 sec)</div><div class="line"></div><div class="line">mysql&gt; alter table stu add primary key (id)</div><div class="line">Query OK, 0 rows affected (0.01 sec)</div><div class="line">Records: 0  Duplicates: 0  Warnings: 0</div></pre></td></tr></table></figure>
<h5 id="查看主键"><a href="#查看主键" class="headerlink" title="查看主键"></a>查看主键</h5><p><code>mysql&gt;desc stu;</code></p>
<h5 id="创建组合键"><a href="#创建组合键" class="headerlink" title="创建组合键"></a>创建组合键</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">mysql&gt; create table stu(</div><div class="line">    -&gt; id int,</div><div class="line">    -&gt; name varchar(20),</div><div class="line">    -&gt; primary key(id,name)</div><div class="line">    -&gt; );</div><div class="line">Query OK, 0 rows affected (0.00 sec)</div></pre></td></tr></table></figure>
<blockquote>
<p>也可以通过更改表的方式来创建组合键<br>alter table stu add primary key(id,name)</p>
</blockquote>
<h5 id="删除主键"><a href="#删除主键" class="headerlink" title="删除主键"></a>删除主键</h5><p><code>mysql&gt;alter table stu drop primary key;</code></p>
<h5 id="选择主键的原则"><a href="#选择主键的原则" class="headerlink" title="选择主键的原则"></a>选择主键的原则</h5><p>1、    最少性：尽量选择一个字段做主键<br>2、    稳定性：尽量选择更新少的列做主键<br>3、    尽量选择数字型的列做主键</p>
<h5 id="主键思考题"><a href="#主键思考题" class="headerlink" title="主键思考题"></a>主键思考题</h5><blockquote>
<p>在主键列输入的数值，允许为空吗?                不能为空<br>一个表可以有多个主键吗?                            不能<br>在一个学校数据库中，如果一个学校内允许重名的学员，但是一个班级内不允许学员重名，可以组合班级和姓名两个字段一起来作为主键吗？可以<br>标识列（自动增长列）允许为字符数据类型吗？        不允许<br>表中没有合适的列作为主键怎么办？                添加一个自动增长列<br>   如果标识列A的初始值为1，增长量为1，则输入三行数据以后，再删除两行，下次再输入数据行的时候，标识值从多少开始？  从4开始</p>
</blockquote>
<h4 id="列属性——唯一键"><a href="#列属性——唯一键" class="headerlink" title="列属性——唯一键"></a>列属性——唯一键</h4><p>特点：不能重复，可以为空<br>一个表可以有多个唯一键<br>作用：<br>1、    保证数据完整性<br>2、    加快数据访问</p>
<h5 id="添加唯一键【创建表的时候添加唯一键】"><a href="#添加唯一键【创建表的时候添加唯一键】" class="headerlink" title="添加唯一键【创建表的时候添加唯一键】"></a>添加唯一键【创建表的时候添加唯一键】</h5><p>unique key<br>unique </p>
<h5 id="添加唯一键【创建表的时候添加唯一键】-1"><a href="#添加唯一键【创建表的时候添加唯一键】-1" class="headerlink" title="添加唯一键【创建表的时候添加唯一键】"></a>添加唯一键【创建表的时候添加唯一键】</h5><p>unique key(stuname)<br>unique(stuadd)</p>
<h5 id="设置名字的唯一键"><a href="#设置名字的唯一键" class="headerlink" title="设置名字的唯一键"></a>设置名字的唯一键</h5><p><code>unique key `name` (`stuname`)</code><br>name：唯一键名字<br>stuname：字段名字</p>
<h5 id="添加唯一键【修改表的时候添加唯一键】"><a href="#添加唯一键【修改表的时候添加唯一键】" class="headerlink" title="添加唯一键【修改表的时候添加唯一键】"></a>添加唯一键【修改表的时候添加唯一键】</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">mysql&gt; create table stu(</div><div class="line">    -&gt; id int primary key,</div><div class="line">    -&gt; stuname varchar(20),</div><div class="line">    -&gt; stuadd varchar(100)</div><div class="line">    -&gt; );</div><div class="line">Query OK, 0 rows affected (0.00 sec)</div></pre></td></tr></table></figure>
<p>添加唯一键</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">mysql&gt; alter table stu add unique key(stuname);   --key可以省略</div><div class="line">mysql&gt; alter table stu add unique (stuadd);</div></pre></td></tr></table></figure>
<p>一次添加多个唯一键<br><code>mysql&gt;alter table stu add unique(stuname),add unique(stuadd);</code></p>
<h5 id="查看唯一键"><a href="#查看唯一键" class="headerlink" title="查看唯一键"></a>查看唯一键</h5><p><code>mysql&gt;show create talbe stu\G</code></p>
<h5 id="添加组合唯一键"><a href="#添加组合唯一键" class="headerlink" title="添加组合唯一键"></a>添加组合唯一键</h5><h5 id="删除唯一键"><a href="#删除唯一键" class="headerlink" title="删除唯一键"></a>删除唯一键</h5><p>通过唯一键的名字来删除唯一键<br>语法：<code>alter table 表名 drop index 唯一键名称</code><br><code>mysql&gt;alter talbe stu drop index stuname;</code></p>
<h5 id="列属性——备注（comment）"><a href="#列属性——备注（comment）" class="headerlink" title="列属性——备注（comment）"></a>列属性——备注（comment）</h5><h5 id="SQL注释"><a href="#SQL注释" class="headerlink" title="SQL注释"></a>SQL注释</h5><p>单行注释：–或#<br>多行注释：/<em>    </em>/</p>
<h4 id="数据完整性"><a href="#数据完整性" class="headerlink" title="数据完整性"></a>数据完整性</h4><h5 id="保证实体完整性"><a href="#保证实体完整性" class="headerlink" title="保证实体完整性"></a>保证实体完整性</h5><p>1、    主键约束<br>2、    唯一约束<br>3、    自动增长列</p>
<h5 id="保证域完整性"><a href="#保证域完整性" class="headerlink" title="保证域完整性"></a>保证域完整性</h5><p>1、    数据类型约束<br>2、    非空约束<br>3、    默认值约束</p>
<h5 id="保证引用完整性"><a href="#保证引用完整性" class="headerlink" title="保证引用完整性"></a>保证引用完整性</h5><p>1、外键约束：从表中的公共字段是主表的外键</p>
<h5 id="保证自定义完整性"><a href="#保证自定义完整性" class="headerlink" title="保证自定义完整性"></a>保证自定义完整性</h5><p>1、    存储过程<br>2、    触发器</p>
<h5 id="主表和从表"><a href="#主表和从表" class="headerlink" title="主表和从表"></a>主表和从表</h5><p>两个表建立关系（两个表只要有公共字段就有关系），一个表称为主表，一个表称为从表。<br>外键约束可以实现：<br>1、    主表中没有的从表中不允许插入<br>2、    从表中有的主表中不允许删除<br>3、    不能更改主表中的值而导致从表中的记录孤立存在。<br>4、    先删除从表，再删除主表</p>
<h4 id="外键（foreign-key）"><a href="#外键（foreign-key）" class="headerlink" title="外键（foreign key）"></a>外键（foreign key）</h4><p>1、    外键：从表中的公共字段，公共字段的名字可以不一样，但是数据类型必须一样。<br>2、    外键约束用来保证引用完整性</p>
<h5 id="添加外键"><a href="#添加外键" class="headerlink" title="添加外键"></a>添加外键</h5><p><strong>foreign key (id) references stuinfo(stuno);</strong><br>方法一：创建表的时候添加外键</p>
<p>references：参照</p>
<p>测试：</p>
<ul>
<li>主表中没有的，从表中不允许插入</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">先插主表，在插从表</div><div class="line"></div><div class="line">mysql&gt; insert into stuinfo values (1,&apos;tom&apos;);</div><div class="line">Query OK, 1 row affected (0.00 sec)</div><div class="line">mysql&gt; insert into stumarks values (1,77);</div><div class="line">Query OK, 1 row affected (0.00 sec)</div></pre></td></tr></table></figure>
<ul>
<li><p>从表中有的，主表中不能删除</p>
</li>
<li><p>不能更改主表的数据后使得从表的数据孤立</p>
</li>
</ul>
<p>方法二：修改表的时候添加外键<br>语法：<code>alter table stumarks add foreign key (id) references stuinfo(stuno);</code></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div></pre></td><td class="code"><pre><div class="line">mysql&gt; create table stuinfo(</div><div class="line">    -&gt; stuno char(4) primary key,</div><div class="line">    -&gt; stuname varchar(20) not null</div><div class="line">    -&gt; );</div><div class="line">Query OK, 0 rows affected (0.00 sec)</div><div class="line"></div><div class="line">mysql&gt; create table stumarks(</div><div class="line">    -&gt; id char(4) primary key,</div><div class="line">    -&gt; score int</div><div class="line">    -&gt; );</div><div class="line">Query OK, 0 rows affected (0.00 sec)</div><div class="line"></div><div class="line">mysql&gt; alter table stumarks add foreign key (id) references stuinfo(stuno);</div><div class="line">Query OK, 0 rows affected (0.01 sec)</div><div class="line">Records: 0  Duplicates: 0  Warnings: 0</div></pre></td></tr></table></figure>
<blockquote>
<p>要创建外键必须是innodb引擎，myisam不支持外键约束</p>
</blockquote>
<p><strong>创建外键的时候，给外键取名</strong><br><code>alter table stumarks add constraint `FK1` foreign key(id) references stuinfo(stuno);</code></p>
<blockquote>
<p>constraint：约束</p>
</blockquote>
<h5 id="删除外键"><a href="#删除外键" class="headerlink" title="删除外键"></a>删除外键</h5><p>通过外键的名字删除外键<br>语法：<code>alter table 表名 drop foreign key `外键名` </code></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div></pre></td><td class="code"><pre><div class="line">mysql&gt;alter talbe stumarks drop foreign key `FK1`</div></pre></td></tr></table></figure>
<blockquote>
<p>如果要在某个字段上添加外键约束，改字段必须要有索引才可以。如果该字段已经存在索引，则直接使用，否则MySQL自动生成索引。</p>
</blockquote>
<h5 id="外键操作"><a href="#外键操作" class="headerlink" title="外键操作"></a>外键操作</h5><p>1、    严格操作（前面讲的是严格操作）<br>2、    置空操作（set null）：如果主表记录删除或更新，从表置空<br>3、    级联操作（cascade）：如果主表记录删除或更新，从表级联</p>
<blockquote>
<p>一般来说：主表删除的时候，从表置空操作，主表更新的时候，从表级联操作。<br>语法：foreign key(外键) references 主表(关键字段) [主表删除时候的动作] [主表更新时候的动作]</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">mysql&gt; create table stumarks(</div><div class="line">    -&gt; id int auto_increment primary key,</div><div class="line">    -&gt; stuno char(4),</div><div class="line">    -&gt; stuscore tinyint(3),</div><div class="line">    -&gt; foreign key(stuno) references stuinfo(stuno) on delete set null on update cascade</div><div class="line">    -&gt; );</div><div class="line">Query OK, 0 rows affected (0.03 sec)</div></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div></pre></td><td class="code"><pre><div class="line">--错误案例--</div><div class="line">create table stuinfo(</div><div class="line">stuno char(4) primary key,</div><div class="line">stuname varchar(20) not null</div><div class="line">);</div><div class="line"></div><div class="line">create table stumarks(</div><div class="line">id char(4) primary key,</div><div class="line">score int</div><div class="line">);</div><div class="line"></div><div class="line">alter table stumarks add constraint FK1 foreign key (id) references stuinfo(stuno) on delete set null on update cascade;</div><div class="line"></div><div class="line">--正确案例--</div><div class="line">create table stuinfo(</div><div class="line">stuno char(4) primary key,</div><div class="line">stuname varchar(20) not null</div><div class="line">);</div><div class="line"></div><div class="line">create table stumarks(</div><div class="line">id1 char(4) primary key,</div><div class="line">id char(4),</div><div class="line">score int</div><div class="line">);</div><div class="line"></div><div class="line">alter table stumarks add constraint FK1 foreign key (id) references stuinfo(stuno) on delete set null on update cascade;</div></pre></td></tr></table></figure>
<blockquote>
<p>使用alter修改表 去创建外键时，是否不能够同时指定制空约束和级联约束？<br>主键不能set null ,所以外键表中新增主键，将外键作为非主键，此问题与alter的设置无关<br><code>foreign key (stuno) references stuinfo(stuno) on delete set null on update cascade;</code></p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div><div class="line">48</div><div class="line">49</div><div class="line">50</div><div class="line">51</div><div class="line">52</div><div class="line">53</div><div class="line">54</div><div class="line">55</div><div class="line">56</div><div class="line">57</div><div class="line">58</div><div class="line">59</div><div class="line">60</div><div class="line">61</div><div class="line">62</div><div class="line">63</div></pre></td><td class="code"><pre><div class="line">mysql&gt; create table stuinfo(</div><div class="line">    -&gt; stuno char(4) primary key,</div><div class="line">    -&gt; stuname varchar(20) not null</div><div class="line">    -&gt; );</div><div class="line">Query OK, 0 rows affected (0.02 sec)</div><div class="line">//主键与非主键之间的关系，主键是不能set null的，所有使用非主键作为外键</div><div class="line">mysql&gt; create table stumarks(</div><div class="line">    -&gt; id int auto_increment primary key,</div><div class="line">    -&gt; stuno char(4),</div><div class="line">	    -&gt; score int,</div><div class="line">	    -&gt; foreign key (stuno) references stuinfo(stuno) on delete set null on update cascade</div><div class="line">    -&gt; );</div><div class="line">Query OK, 0 rows affected (0.00 sec)</div><div class="line"></div><div class="line">mysql&gt; insert into stuinfo values (&apos;1001&apos;,&apos;tom&apos;),(&apos;1002&apos;,&apos;berry&apos;);</div><div class="line">Query OK, 2 rows affected (0.00 sec)</div><div class="line">Records: 2  Duplicates: 0  Warnings: 0</div><div class="line"></div><div class="line">mysql&gt; insert into stumarks values (null,&apos;1001&apos;,88),(null,&apos;1002&apos;,99);</div><div class="line">Query OK, 2 rows affected (0.00 sec)</div><div class="line">Records: 2  Duplicates: 0  Warnings: 0</div><div class="line">mysql&gt; select * from stumarks;</div><div class="line">+----+-------+-------+</div><div class="line">| id | stuno | score |</div><div class="line">+----+-------+-------+</div><div class="line">|  1 | 1001  |    88 |</div><div class="line">|  2 | 1002  |    99 |</div><div class="line">+----+-------+-------+</div><div class="line">2 rows in set (0.00 sec)</div><div class="line"></div><div class="line">mysql&gt; select * from stuinfo;</div><div class="line">+-------+---------+</div><div class="line">| stuno | stuname |</div><div class="line">+-------+---------+</div><div class="line">| 1001  | tom     |</div><div class="line">| 1002  | berry   |</div><div class="line">+-------+---------+</div><div class="line">2 rows in set (0.00 sec)</div><div class="line"></div><div class="line">mysql&gt; delete from stuinfo where stuno=&apos;1001&apos;;</div><div class="line">Query OK, 1 row affected (0.00 sec)</div><div class="line"></div><div class="line">mysql&gt; select * from stumarks;</div><div class="line">+----+-------+-------+</div><div class="line">| id | stuno | score |</div><div class="line">+----+-------+-------+</div><div class="line">|  1 | NULL  |    88 |</div><div class="line">|  2 | 1002  |    99 |</div><div class="line">+----+-------+-------+</div><div class="line">2 rows in set (0.00 sec)</div><div class="line"></div><div class="line">mysql&gt; update stuinfo set stuno=&apos;1003&apos; where stuno=&apos;1002&apos;;</div><div class="line">Query OK, 1 row affected (0.00 sec)</div><div class="line">Rows matched: 1  Changed: 1  Warnings: 0</div><div class="line"></div><div class="line">mysql&gt; select * from stumarks;</div><div class="line">+----+-------+-------+</div><div class="line">| id | stuno | score |</div><div class="line">+----+-------+-------+</div><div class="line">|  1 | NULL  |    88 |</div><div class="line">|  2 | 1003  |    99 |</div><div class="line">+----+-------+-------+</div><div class="line">2 rows in set (0.00 sec)</div></pre></td></tr></table></figure>
<h3 id="再来一戳，外键级联"><a href="#再来一戳，外键级联" class="headerlink" title="再来一戳，外键级联"></a>再来一戳，外键级联</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div></pre></td><td class="code"><pre><div class="line">ALTER TABLE stumarks DROP FOREIGN KEY `FK1`;</div><div class="line"></div><div class="line">DROP TABLE</div><div class="line">IF EXISTS stuinfo;</div><div class="line"></div><div class="line">DROP TABLE</div><div class="line">IF EXISTS stumarks;</div><div class="line"></div><div class="line">CREATE TABLE stuinfo(</div><div class="line">    stuno CHAR(4) PRIMARY KEY ,</div><div class="line">    stuname VARCHAR(10)</div><div class="line">);</div><div class="line"></div><div class="line">CREATE TABLE stumarks(</div><div class="line">    id INT auto_increment PRIMARY KEY ,</div><div class="line">    stuno CHAR(4) UNIQUE KEY,</div><div class="line">    stuscore TINYINT(3) ,</div><div class="line">    CONSTRAINT `FK1` FOREIGN KEY(stuno) REFERENCES stuinfo(stuno) ON DELETE</div><div class="line">SET NULL ON UPDATE CASCADE</div><div class="line">);</div></pre></td></tr></table></figure>
<blockquote>
<p>经验总结：设置级联外键由于 on delete set null 的原因不能设置外键为主键，解决外键数据完整的方法是给外键增加为一件 unique key;</p>
</blockquote>

          
        
      
    </div>

    <div>
      
    </div>

    <div>
      
    </div>

    <footer class="post-footer">
      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </article>


    
      

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                
                <a class="post-title-link" href="/20160829-1.html" itemprop="url">
                  Day7-MySQL 知识、数据库、数据表
                </a>
              
            
          </h1>
        

        <div class="post-meta">
        
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">发表于</span>
            <time itemprop="dateCreated" datetime="2016-08-29T17:18:51+08:00" content="2016-08-29">
              2016-08-29
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/MySQL/" itemprop="url" rel="index">
                    <span itemprop="name">MySQL</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/20160829-1.html#comments" itemprop="discussionUrl">
                  <span class="post-comments-count ds-thread-count" data-thread-key="20160829-1.html" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          

          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <h3 id="SQL-DML-和-DDL"><a href="#SQL-DML-和-DDL" class="headerlink" title="SQL DML 和 DDL"></a>SQL DML 和 DDL</h3><p>可以把 SQL 分为两个部分：数据操作语言 (DML) 和 数据定义语言 (DDL)。<br>SQL (结构化查询语言)是用于执行查询的语法。但是 SQL 语言也包含用于更新、插入和删除记录的语法。<br>查询和更新指令构成了 SQL 的 DML 部分：<br>SELECT - 从数据库表中获取数据<br>UPDATE - 更新数据库表中的数据<br>DELETE - 从数据库表中删除数据<br>INSERT INTO - 向数据库表中插入数据<br>SQL 的数据定义语言 (DDL) 部分使我们有能力创建或删除表格。我们也可以定义索引（键），规定表之间的链接，以及施加表间的约束。<br>SQL 中最重要的 DDL 语句:<br>CREATE DATABASE - 创建新数据库<br>ALTER DATABASE - 修改数据库<br>CREATE TABLE - 创建新表<br>ALTER TABLE - 变更（改变）数据库表<br>DROP TABLE - 删除表<br>CREATE INDEX - 创建索引（搜索键）<br>DROP INDEX - 删除索引</p>
<h3 id="数据库发展史"><a href="#数据库发展史" class="headerlink" title="数据库发展史"></a>数据库发展史</h3><p>文件系统-》层次模型-》网状模型-》关系型数据库<br>优点：解决了导航的问题、数据完整性得到了解决</p>
<p>缺点：多表查询效率低<br>解决方法：使用NOSQL（非关系型数据库，Redis、mongodb等等），在数据库中按照键值对来存储。</p>
<h3 id="SQL"><a href="#SQL" class="headerlink" title="SQL"></a>SQL</h3><p>结构化查询语言，标准SQL，也叫SQL-92</p>
<p>access    微软    SQL<br>SQL Server    微软    T-SQL<br>Oracle    甲骨文    PL/SQL<br>MySQL    被甲骨文收购    MySQL</p>
<h3 id="windows-服务开启"><a href="#windows-服务开启" class="headerlink" title="windows 服务开启"></a>windows 服务开启</h3><p>win+R    services.msc 打开服务面板<br>net start    查看已经开启的服务</p>
<p><code>net start mysql</code>      启动服务<br><code>net stop mysql</code>     关闭服务</p>
<h3 id="MySQL客户端连接服务器"><a href="#MySQL客户端连接服务器" class="headerlink" title="MySQL客户端连接服务器"></a>MySQL客户端连接服务器</h3><p>安装文件目录下的：<code>MySQL 5.5 Command Line Client</code><br>navicat 客户端<br>PHPmyadmin 客户端<br>设置环境变量后：<code>mysql  -hlocalhost  -uroot -proot  -P3306</code>   (如果MySQL服务器在本地，IP地址可以省略；如果MySQL服务器用的是3306端口，-P也是可以省略的)</p>
<h3 id="退出登录"><a href="#退出登录" class="headerlink" title="退出登录"></a>退出登录</h3><p>exit;<br>quit;<br>\q;<br>MySQL中的命令后面要加分号，windows命令行的命令后面不用加分号</p>
<h3 id="数据库基本概念"><a href="#数据库基本概念" class="headerlink" title="数据库基本概念"></a>数据库基本概念</h3><p>数据库：数据库中存放的是表，一个数据库中可以存放多个表<br>表：用来存放数据<br>关系：两个表的公共字段<br>行：记录，也是实体<br>列：字段，也是属性<br>表结构    行    列<br>表数据    记录    字段<br>面向对象    实体    属性</p>
<blockquote>
<p>表的冗余只能减少，不能杜绝</p>
</blockquote>
<p>数据完整性：正确的数据类型，准确的数据范围</p>
<h3 id="数据库操作"><a href="#数据库操作" class="headerlink" title="数据库操作"></a>数据库操作</h3><h4 id="连接数据库"><a href="#连接数据库" class="headerlink" title="连接数据库"></a>连接数据库</h4><p><code>Mac xampp ：$ /Applications/XAMPP/xamppfiles/bin/mysql -hlocalhost -uroot -p -P3306</code><br>密码初始为空；</p>
<h4 id="创建数据库"><a href="#创建数据库" class="headerlink" title="创建数据库"></a>创建数据库</h4><p>语法：<code>create database [if not exists] 数据名</code></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">mysql&gt; create database if not exists uiste;</div><div class="line">Query OK, 1 row affected (0.00 sec)</div></pre></td></tr></table></figure>
<p>问题一：</p>
<blockquote>
<p>如果创建的数据库已存在，就会报错<br>解决：创建数据库的时候判断一下数据库是否存在，如果不存在再创建</p>
</blockquote>
<p>问题二：</p>
<blockquote>
<p>如果数据库名是关键字和特殊字符要报错<br>解决：在特殊字符、关键字行加上反引号<br><code>create database `$@%`;</code></p>
</blockquote>
<p><strong>为了创建数据库时万无一失，我们可以在所有的数据库名上加上反引号</strong></p>
<h4 id="MySQL数据库的目录"><a href="#MySQL数据库的目录" class="headerlink" title="MySQL数据库的目录"></a>MySQL数据库的目录</h4><p>数据库文件保存的路径在安装MySQL的时候就配置好。<br>也可以在<code>my.ini</code>配置文件中更改</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">#Path to the database root</div><div class="line">datadir = &quot;F:/wamp/mysql/Data/&quot;</div></pre></td></tr></table></figure>
<p>Mac xampp 数据库文件夹：<br><code>/Applications /XAMPP/xamppfiles/var/mysql</code></p>
<p>创建一个数据库，就对应一个文件夹，在文件夹中有一个db.opt文件。在此文件中设置数据库的字符集和校对集</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">default-character-set = utf8</div><div class="line">default-collation = utf_general_ci</div></pre></td></tr></table></figure>
<h4 id="显示所有数据库【show-databases】"><a href="#显示所有数据库【show-databases】" class="headerlink" title="显示所有数据库【show databases】"></a>显示所有数据库【show databases】</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div></pre></td><td class="code"><pre><div class="line">mysql&gt; show databases;</div><div class="line">+--------------------+</div><div class="line">| Database           |</div><div class="line">+--------------------+</div><div class="line">| information_schema |</div><div class="line">| cdcol              |</div><div class="line">| dedecms            |</div><div class="line">| mysql              |</div><div class="line">| performance_schema |</div><div class="line">| phpmyadmin         |</div><div class="line">| test               |</div><div class="line">| uiste              |</div><div class="line">+--------------------+</div><div class="line">8 rows in set (0.00 sec)</div></pre></td></tr></table></figure>
<blockquote>
<p>information_schema：存储了MySQL服务器管理数据库的信息。比如：数据库名、表、字段名、数据类型及访问权限等等<br>performance_schema：MySQL5.5新增的表，用来保存数据库服务器性能的参数<br>mysql：MySQL系统数据库，保存的登录用户名，密码，以及每个用户的权限等等<br>test：给用户学习和测试的数据库。</p>
</blockquote>
<h4 id="删除数据库"><a href="#删除数据库" class="headerlink" title="删除数据库"></a>删除数据库</h4><p>语法：<code>drop database [if exists] `数据库名` </code></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div></pre></td><td class="code"><pre><div class="line">mysql&gt; drop database if exists uiste;</div><div class="line">Query OK, 0 rows affected (0.00 sec)</div><div class="line"></div><div class="line">mysql&gt; show databases;</div><div class="line">+--------------------+</div><div class="line">| Database           |</div><div class="line">+--------------------+</div><div class="line">| information_schema |</div><div class="line">| cdcol              |</div><div class="line">| dedecms            |</div><div class="line">| mysql              |</div><div class="line">| performance_schema |</div><div class="line">| phpmyadmin         |</div><div class="line">| test               |</div><div class="line">+--------------------+</div><div class="line">7 rows in set (0.00 sec)</div></pre></td></tr></table></figure>
<p>问题：</p>
<blockquote>
<p>如果删除的数据库不存在，会报错<br>解决：删除之前判断一下，如果存在就删除</p>
</blockquote>
<h4 id="显示创建数据库的语句"><a href="#显示创建数据库的语句" class="headerlink" title="显示创建数据库的语句"></a>显示创建数据库的语句</h4><p>语法：<code>show create database 数据库名</code></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">mysql&gt; show create database uiste;</div><div class="line">+----------+------------------------------------------------------------------+</div><div class="line">| Database | Create Database                                                  |</div><div class="line">+----------+------------------------------------------------------------------+</div><div class="line">| uiste    | CREATE DATABASE `uiste` /*!40100 DEFAULT CHARACTER SET latin1 */ |</div><div class="line">+----------+------------------------------------------------------------------+</div><div class="line">1 row in set (0.00 sec)</div></pre></td></tr></table></figure>
<h4 id="修改数据库字符编码"><a href="#修改数据库字符编码" class="headerlink" title="修改数据库字符编码"></a>修改数据库字符编码</h4><p>语法：<code>alter database `数据库名` charset=字符编码</code></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line">mysql&gt; alter database uiste charset=utf8;</div><div class="line">Query OK, 1 row affected (0.01 sec)</div><div class="line"></div><div class="line">mysql&gt; show create database uiste;</div><div class="line">+----------+----------------------------------------------------------------+</div><div class="line">| Database | Create Database                                                |</div><div class="line">+----------+----------------------------------------------------------------+</div><div class="line">| uiste    | CREATE DATABASE `uiste` /*!40100 DEFAULT CHARACTER SET utf8 */ |</div><div class="line">+----------+----------------------------------------------------------------+</div><div class="line">1 row in set (0.00 sec)</div></pre></td></tr></table></figure>
<h4 id="选择数据库"><a href="#选择数据库" class="headerlink" title="选择数据库"></a>选择数据库</h4><p>语法：<code>use `数据库名</code></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">mysql&gt; use uiste;</div><div class="line">Database changed</div></pre></td></tr></table></figure>
<h3 id="表的操作"><a href="#表的操作" class="headerlink" title="表的操作"></a>表的操作</h3><h4 id="创建表"><a href="#创建表" class="headerlink" title="创建表"></a>创建表</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div></pre></td><td class="code"><pre><div class="line">create table [if not exists] `表名`(</div><div class="line">	`字段名` 数据类型 [null|not null] [default] [auto_increment] [primary key] [comment],</div><div class="line">	字段名 数据类型 …</div><div class="line">)[engine=存储引擎] [charset=字符编码]</div><div class="line"></div><div class="line">null|not null		是否为空</div><div class="line">default:			默认值</div><div class="line">auto_increment	自动增长</div><div class="line">primary key		主键</div><div class="line">comment:			备注</div><div class="line">engine				引擎</div></pre></td></tr></table></figure>
<blockquote>
<p>表名和字段名如果用了关键字，要用反引号引起来。</p>
</blockquote>
<p>创建简单的表</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">mysql&gt; create table student(</div><div class="line">    -&gt; id int not null auto_increment primary key comment &apos;学生编号&apos;,</div><div class="line">    -&gt; name varchar(10) not null comment &apos;学生姓名&apos;,</div><div class="line">    -&gt; sex char(4) default &apos;男&apos;);</div><div class="line">Query OK, 0 rows affected (0.03 sec)</div></pre></td></tr></table></figure>
<p>创建复杂的表</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">mysql&gt; create table `goods`(</div><div class="line">    -&gt; `id` int auto_increment primary key comment &apos;商品编号&apos;,</div><div class="line">    -&gt; `name` varchar(20) not null comment &apos;商品名称&apos;,</div><div class="line">    -&gt; `add` varchar(100) not null default &apos;地址不详&apos; comment &apos;商品产地&apos;</div><div class="line">    -&gt; )engine=innodb charset=utf8 comment &apos;商品表&apos;;</div><div class="line">Query OK, 0 rows affected (0.05 sec)</div></pre></td></tr></table></figure>
<blockquote>
<p>create table 数据库名.表名，用于给指定的数据库创建表</p>
</blockquote>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">mysql&gt; create table uiste.teacher(</div><div class="line">    -&gt; id int auto_increment primary key,</div><div class="line">    -&gt; name varchar(16) not null);</div><div class="line">Query OK, 0 rows affected (0.02 sec)</div></pre></td></tr></table></figure>
<h4 id="数据表文件"><a href="#数据表文件" class="headerlink" title="数据表文件"></a>数据表文件</h4><ul>
<li>一个数据库对应一个文件夹</li>
<li>一个表对应一个或多个文件夹<br>引擎是myisam，一个表对应三个文件(不支持外键约束)<blockquote>
<p>t1.frm  表结构<br>t1.MYD  表数据<br>t1.MYI  表索引<br>引擎是innodb,一个表对应一个表结构文件</p>
</blockquote>
</li>
</ul>
<blockquote>
<p>所有的innodb引擎的数据统一的存放在data\ibdata1文件中。如果数据量很大，MySQL会自动的创建ibdata2，ibdata3，…，目的就是为了便于管理。</p>
</blockquote>
<p>constraint：约束</p>
<h4 id="显示所有表"><a href="#显示所有表" class="headerlink" title="显示所有表"></a>显示所有表</h4><p>语法：<code>show tables;</code></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">mysql&gt; show tables;</div><div class="line">+-----------------+</div><div class="line">| Tables_in_uiste |</div><div class="line">+-----------------+</div><div class="line">| student         |</div><div class="line">| teacher         |</div><div class="line">+-----------------+</div><div class="line">2 rows in set (0.00 sec)</div></pre></td></tr></table></figure>
<h4 id="显示创建表的语句"><a href="#显示创建表的语句" class="headerlink" title="显示创建表的语句"></a>显示创建表的语句</h4><p>语法：<code>show create table `表名` </code></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div></pre></td><td class="code"><pre><div class="line">mysql&gt; show create table student;</div><div class="line">+---------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+</div><div class="line">| Table   | Create Table                                                                                                                                                                                                                           |</div><div class="line">+---------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+</div><div class="line">| student | CREATE TABLE `student` (</div><div class="line">  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT &apos;学生编号&apos;,</div><div class="line">  `name` varchar(10) NOT NULL COMMENT &apos;学生姓名&apos;,</div><div class="line">  `sex` char(4) DEFAULT &apos;男&apos;,</div><div class="line">  PRIMARY KEY (`id`)</div><div class="line">) ENGINE=InnoDB DEFAULT CHARSET=utf8          |</div><div class="line">+---------+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+</div><div class="line">1 row in set (0.01 sec)</div></pre></td></tr></table></figure>
<p><strong>将两个字段竖着排列</strong><br>语法：<code>show create table `表名`\G</code></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line">mysql&gt; show create table student \G</div><div class="line">*************************** 1. row ***************************</div><div class="line">       Table: student</div><div class="line">Create Table: CREATE TABLE `student` (</div><div class="line">  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT &apos;学生编号&apos;,</div><div class="line">  `name` varchar(10) NOT NULL COMMENT &apos;学生姓名&apos;,</div><div class="line">  `sex` char(4) DEFAULT &apos;男&apos;,</div><div class="line">  PRIMARY KEY (`id`)</div><div class="line">) ENGINE=InnoDB DEFAULT CHARSET=utf8</div><div class="line">1 row in set (0.00 sec)</div></pre></td></tr></table></figure>
<h4 id="查看表结构"><a href="#查看表结构" class="headerlink" title="查看表结构"></a>查看表结构</h4><p>语法：<code>desc[ribe] `表名` </code></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div></pre></td><td class="code"><pre><div class="line">mysql&gt; desc student;</div><div class="line">+-------+-------------+------+-----+---------+----------------+</div><div class="line">| Field | Type        | Null | Key | Default | Extra          |</div><div class="line">+-------+-------------+------+-----+---------+----------------+</div><div class="line">| id    | int(11)     | NO   | PRI | NULL    | auto_increment |</div><div class="line">| name  | varchar(10) | NO   |     | NULL    |                |</div><div class="line">| sex   | char(4)     | YES  |     | 男      |                |</div><div class="line">+-------+-------------+------+-----+---------+----------------+</div><div class="line">3 rows in set (0.01 sec)</div><div class="line"></div><div class="line">mysql&gt; describe student;</div><div class="line">+-------+-------------+------+-----+---------+----------------+</div><div class="line">| Field | Type        | Null | Key | Default | Extra          |</div><div class="line">+-------+-------------+------+-----+---------+----------------+</div><div class="line">| id    | int(11)     | NO   | PRI | NULL    | auto_increment |</div><div class="line">| name  | varchar(10) | NO   |     | NULL    |                |</div><div class="line">| sex   | char(4)     | YES  |     | 男      |                |</div><div class="line">+-------+-------------+------+-----+---------+----------------+</div><div class="line">3 rows in set (0.01 sec)</div></pre></td></tr></table></figure>
<blockquote>
<p>desc 是 describe 的简写</p>
</blockquote>
<h4 id="复制表"><a href="#复制表" class="headerlink" title="复制表"></a>复制表</h4><p>语法一：<code>create table 新表 select 字段 from 旧表</code></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">mysql&gt; create table student2 select * from student;</div><div class="line">Query OK, 0 rows affected (0.02 sec)</div><div class="line">Records: 0  Duplicates: 0  Warnings: 0</div></pre></td></tr></table></figure>
<blockquote>
<p>特点：不能复制父表的键，能够复制父表的数据</p>
</blockquote>
<p>语法二：create table 新表 like 旧表</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">mysql&gt; create table student3 like student;</div><div class="line">Query OK, 0 rows affected (0.03 sec)</div></pre></td></tr></table></figure>
<blockquote>
<p>特点：只能复制表结构，不能复制表数据</p>
</blockquote>
<h4 id="删除表"><a href="#删除表" class="headerlink" title="删除表"></a>删除表</h4><p>语法：<code>drop table [if exists] 表1，表2,…</code></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">mysql&gt; drop table if exists student2;</div><div class="line">Query OK, 0 rows affected (0.01 sec)</div></pre></td></tr></table></figure>
<blockquote>
<p>如果删除一个不存在的表就会报错，删除的时候可以判断一下，存在就删除</p>
</blockquote>
<p>可以一次删除多个表</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">mysql&gt; drop tables if exists student2,student3;</div><div class="line">Query OK, 0 rows affected (0.01 sec)</div></pre></td></tr></table></figure>
<h4 id="修改表"><a href="#修改表" class="headerlink" title="修改表"></a>修改表</h4><p>语法：<code>alter table 表名</code></p>
<h5 id="添加字段"><a href="#添加字段" class="headerlink" title="添加字段"></a>添加字段</h5><p>语法：<code>alter table 表名add [column] 字段名 数据类型 [位置]</code></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">mysql&gt; alter table student add age int(8) after name;</div><div class="line">Query OK, 0 rows affected (0.20 sec)</div><div class="line">Records: 0  Duplicates: 0  Warnings: 0</div></pre></td></tr></table></figure>
<blockquote>
<p>默认字段放在表的最后<br>添加 <code>first</code> 字段放在表的第一位<br>添加 <code>after name</code> 放在 name 字段之后</p>
</blockquote>
<h5 id="删除字段"><a href="#删除字段" class="headerlink" title="删除字段"></a>删除字段</h5><p>语法：<code>alter table 表 drop [column] 字段名</code></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">mysql&gt; alter table student drop age;</div><div class="line">Query OK, 0 rows affected (0.05 sec)</div><div class="line">Records: 0  Duplicates: 0  Warnings: 0</div></pre></td></tr></table></figure>
<h5 id="修改字段-改名"><a href="#修改字段-改名" class="headerlink" title="修改字段(改名)"></a>修改字段(改名)</h5><p>语法：<code>alter table 表 change [column] 原字段名 新字段名 数据类型 …</code></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">mysql&gt; alter table student change sex age int(8);</div><div class="line">Query OK, 0 rows affected (0.32 sec)</div><div class="line">Records: 0  Duplicates: 0  Warnings: 0</div></pre></td></tr></table></figure>
<p>同时修改多个字段</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">mysql&gt; alter table student change age myage int(8) comment &apos;我的学生年龄&apos;,change name myname varchar(16) not null comment &apos;我的学生姓名&apos;;</div><div class="line">Query OK, 0 rows affected (0.04 sec)</div><div class="line">Records: 0  Duplicates: 0  Warnings: 0</div></pre></td></tr></table></figure>
<h5 id="修改字段（不改名）"><a href="#修改字段（不改名）" class="headerlink" title="修改字段（不改名）"></a>修改字段（不改名）</h5><p>语法：<code>alter table 表 modify 字段名 字段属性…</code></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">mysql&gt; alter table student modify myage int(3) not null default 18 comment &apos;如果你没 有设置年龄，我就是永远的18岁&apos;;</div><div class="line">Query OK, 0 rows affected (0.02 sec)</div><div class="line">Records: 0  Duplicates: 0  Warnings: 0</div></pre></td></tr></table></figure>
<blockquote>
<p>只更改字段属性</p>
</blockquote>
<h5 id="修改引擎"><a href="#修改引擎" class="headerlink" title="修改引擎"></a>修改引擎</h5><p>语法：<code>alter table 表名 engine=引擎名</code></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">mysql&gt; alter table student engine=myisam;</div><div class="line">Query OK, 0 rows affected (0.18 sec)</div><div class="line">Records: 0  Duplicates: 0  Warnings: 0</div></pre></td></tr></table></figure>
<h5 id="修改表名"><a href="#修改表名" class="headerlink" title="修改表名"></a>修改表名</h5><p>语法：<code>alter table 表名 rename to 新表名</code></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">mysql&gt; alter table student rename to student2;</div><div class="line">Query OK, 0 rows affected (0.00 sec)</div></pre></td></tr></table></figure>
<h5 id="将表移动到其他数据库"><a href="#将表移动到其他数据库" class="headerlink" title="将表移动到其他数据库"></a>将表移动到其他数据库</h5><p>语法：<code>alter table 表名 rename to 数据库名.数据表名</code></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">alter table student2 rename to test.student3;</div><div class="line">Query OK, 0 rows affected (0.01 sec)</div></pre></td></tr></table></figure>
<h4 id="数据操作"><a href="#数据操作" class="headerlink" title="数据操作"></a>数据操作</h4><h5 id="插入数据"><a href="#插入数据" class="headerlink" title="插入数据"></a>插入数据</h5><p>语法：<code>insert into 表名 (字段名, 字段名,…) values (值1, 值1,…)</code></p>
<ul>
<li>插入一条数据</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">mysql&gt; insert into student (id,name,age) values (1,&apos;小兰&apos;,25);</div><div class="line">Query OK, 1 row affected (0.01 sec)</div></pre></td></tr></table></figure>
<blockquote>
<ol>
<li>插入字段名的顺序和数据库字段名的顺序可以不一致</li>
<li>插入值的个数、顺序必须和插入字段名的个数、顺序要一致</li>
</ol>
</blockquote>
<ul>
<li>简写方式：</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">mysql&gt; insert into student values (2,&apos;杜总&apos;,24);</div><div class="line">Query OK, 1 row affected (0.02 sec)</div></pre></td></tr></table></figure>
<blockquote>
<ol>
<li>自动增长列，可以直接插入null。</li>
</ol>
</blockquote>
<ul>
<li>插入默认值和空值</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">mysql&gt; insert into student values (null,&apos;张宝&apos;,null);</div><div class="line">Query OK, 1 row affected (0.01 sec)</div></pre></td></tr></table></figure>
<blockquote>
<p>自动增长列，可以直接插入null<br>default关键字用来插入默认值，null用来插入空值</p>
</blockquote>
<ul>
<li>插入多条数据</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">mysql&gt; insert into student values (null,&apos;小张&apos;,18),(null,&apos;圆哥&apos;,18);</div><div class="line">Query OK, 2 rows affected (0.00 sec)</div><div class="line">Records: 2  Duplicates: 0  Warnings: 0</div></pre></td></tr></table></figure>
<ul>
<li>使用insert…set…插入数据</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">mysql&gt; insert into student set name=&apos;赵哥&apos;,age=54;</div><div class="line">Query OK, 1 row affected (0.01 sec)</div></pre></td></tr></table></figure>
<h5 id="更新数据"><a href="#更新数据" class="headerlink" title="更新数据"></a>更新数据</h5><p>语法：<code>update 表名 set 字段=值 [where 条件] [order by 排序] [limit 限制]</code></p>
<ul>
<li>将id为三的年龄改为30</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">mysql&gt; update student set age=30 where id=3;</div><div class="line">Query OK, 1 row affected (0.01 sec)</div><div class="line">Rows matched: 1  Changed: 1  Warnings: 0</div></pre></td></tr></table></figure>
<blockquote>
<p>需要更改多个内容的时候将需要变更的内容用逗号连接；</p>
</blockquote>
<ul>
<li>将id 从大到小数前3名的学生年龄改为16岁</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">mysql&gt; update student set age=16 order by id desc limit 3;</div><div class="line">Query OK, 3 rows affected (0.01 sec)</div><div class="line">Rows matched: 3  Changed: 3  Warnings: 0</div></pre></td></tr></table></figure>
<h5 id="删除数据"><a href="#删除数据" class="headerlink" title="删除数据"></a>删除数据</h5><p>语法：<code>delete from 表名 [where 条件] [order by 排序] [limit 限制]</code></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">mysql&gt; delete from student where id=9;</div><div class="line">Query OK, 1 row affected (0.00 sec)</div></pre></td></tr></table></figure>
<p>删除id &lt;=7;</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">mysql&gt; delete from student where id&lt;=7;</div><div class="line">Query OK, 7 rows affected (0.00 sec)</div></pre></td></tr></table></figure>
<p>清空表</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">mysql&gt; delete from student;</div><div class="line">Query OK, 0 rows affected (0.00 sec)</div></pre></td></tr></table></figure>
<p>清空表：truncate table 表名</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">mysql&gt; truncate table student;</div><div class="line">Query OK, 0 rows affected (0.02 sec)</div></pre></td></tr></table></figure>
<blockquote>
<p>delete from 表和truncate table 表区别？<br>delete from 表：遍历表记录，一条一条的删除<br>truncate table：将原表销毁，再创建一个同结构的新表。就清空表而言，这种方法效率高。</p>
</blockquote>
<h4 id="字符集"><a href="#字符集" class="headerlink" title="字符集"></a>字符集</h4><p>字符集：字符在保存和传输时对应的二进制编码集合</p>
<h5 id="数据存储时使用字符集"><a href="#数据存储时使用字符集" class="headerlink" title="数据存储时使用字符集"></a>数据存储时使用字符集</h5><p>MySQL可以在服务器上、数据库、表、字段上设置字符集</p>
<blockquote>
<p>脚下留心：一般在数据库和表上设置字符集，每个字段设置字符集太麻烦。</p>
</blockquote>
<h5 id="数据传输时使用字符集"><a href="#数据传输时使用字符集" class="headerlink" title="数据传输时使用字符集"></a>数据传输时使用字符集</h5><p>发现：在插入数据的时候，如果有中文会报错</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">mysql&gt; insert into student values (null,&apos;李白&apos;);</div><div class="line">ERROR 1366 (HY000):Incorrect string value :&apos;\xC0\xEE\xB0\xD7&apos; for column &apos;name&apos;</div></pre></td></tr></table></figure>
<blockquote>
<p>分析：客户端编码和服务器连接层编码必须一致，如果不一致就会报错。</p>
</blockquote>
<p>查看客户端的字符编码</p>
<blockquote>
<p>客户端发送某种编码给服务器，由客户端决定<br>客户端编码不能改变<br>客户端右键——属性——选项——可以查看当前客户端的字符编码（GBK）</p>
</blockquote>
<p>查看服务器的字符编码</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div></pre></td><td class="code"><pre><div class="line">mysql&gt; show variables like &apos;character_set_%&apos;;</div><div class="line">+--------------------------+------------------------------------------------+</div><div class="line">| Variable_name            | Value                                          |</div><div class="line">+--------------------------+------------------------------------------------+</div><div class="line">| character_set_client     | utf8                                           |</div><div class="line">| character_set_connection | utf8                                           |</div><div class="line">| character_set_database   | utf8                                           |</div><div class="line">| character_set_filesystem | binary                                         |</div><div class="line">| character_set_results    | utf8                                           |</div><div class="line">| character_set_server     | latin1                                         |</div><div class="line">| character_set_system     | utf8                                           |</div><div class="line">| character_sets_dir       | /Applications/XAMPP/xamppfiles/share/charsets/ |</div><div class="line">+--------------------------+------------------------------------------------+</div><div class="line">8 rows in set (0.01 sec)</div></pre></td></tr></table></figure>
<blockquote>
<p>解决：只要将服务器的编码设置成gbk就可以解决</p>
</blockquote>
<p>测试：插入中文<br>查询：插入中文</p>
<p>原因：结果返回的是utf8，客户端用gbk来解析，所以乱码<br>解决：服务器按gbk返回即可</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">mysql&gt;set character_set_results=gbk;</div><div class="line">Query OK, 0 rows affected (0.00 sec)</div></pre></td></tr></table></figure>
<p>查询：结果</p>
<blockquote>
<p>总结：客户端编码、<code>character_set_client</code>、<code>character_set_results</code>三个编码的值一致即可操作中文。<br>多学一招：我们只要设置<code>“set names 字符编码”</code>，就可以更改<code>character_set_client</code>、<code>character_set_results</code>的值。</p>
</blockquote>
<h5 id="查看所有字符集"><a href="#查看所有字符集" class="headerlink" title="查看所有字符集"></a>查看所有字符集</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div><div class="line">22</div><div class="line">23</div><div class="line">24</div><div class="line">25</div><div class="line">26</div><div class="line">27</div><div class="line">28</div><div class="line">29</div><div class="line">30</div><div class="line">31</div><div class="line">32</div><div class="line">33</div><div class="line">34</div><div class="line">35</div><div class="line">36</div><div class="line">37</div><div class="line">38</div><div class="line">39</div><div class="line">40</div><div class="line">41</div><div class="line">42</div><div class="line">43</div><div class="line">44</div><div class="line">45</div><div class="line">46</div><div class="line">47</div></pre></td><td class="code"><pre><div class="line"></div><div class="line">mysql&gt; show character set;</div><div class="line">+----------+-----------------------------+---------------------+--------+</div><div class="line">| Charset  | Description                 | Default collation   | Maxlen |</div><div class="line">+----------+-----------------------------+---------------------+--------+</div><div class="line">| big5     | Big5 Traditional Chinese    | big5_chinese_ci     |      2 |</div><div class="line">| dec8     | DEC West European           | dec8_swedish_ci     |      1 |</div><div class="line">| cp850    | DOS West European           | cp850_general_ci    |      1 |</div><div class="line">| hp8      | HP West European            | hp8_english_ci      |      1 |</div><div class="line">| koi8r    | KOI8-R Relcom Russian       | koi8r_general_ci    |      1 |</div><div class="line">| latin1   | cp1252 West European        | latin1_swedish_ci   |      1 |</div><div class="line">| latin2   | ISO 8859-2 Central European | latin2_general_ci   |      1 |</div><div class="line">| swe7     | 7bit Swedish                | swe7_swedish_ci     |      1 |</div><div class="line">| ascii    | US ASCII                    | ascii_general_ci    |      1 |</div><div class="line">| ujis     | EUC-JP Japanese             | ujis_japanese_ci    |      3 |</div><div class="line">| sjis     | Shift-JIS Japanese          | sjis_japanese_ci    |      2 |</div><div class="line">| hebrew   | ISO 8859-8 Hebrew           | hebrew_general_ci   |      1 |</div><div class="line">| tis620   | TIS620 Thai                 | tis620_thai_ci      |      1 |</div><div class="line">| euckr    | EUC-KR Korean               | euckr_korean_ci     |      2 |</div><div class="line">| koi8u    | KOI8-U Ukrainian            | koi8u_general_ci    |      1 |</div><div class="line">| gb2312   | GB2312 Simplified Chinese   | gb2312_chinese_ci   |      2 |</div><div class="line">| greek    | ISO 8859-7 Greek            | greek_general_ci    |      1 |</div><div class="line">| cp1250   | Windows Central European    | cp1250_general_ci   |      1 |</div><div class="line">| gbk      | GBK Simplified Chinese      | gbk_chinese_ci      |      2 |</div><div class="line">| latin5   | ISO 8859-9 Turkish          | latin5_turkish_ci   |      1 |</div><div class="line">| armscii8 | ARMSCII-8 Armenian          | armscii8_general_ci |      1 |</div><div class="line">| utf8     | UTF-8 Unicode               | utf8_general_ci     |      3 |</div><div class="line">| ucs2     | UCS-2 Unicode               | ucs2_general_ci     |      2 |</div><div class="line">| cp866    | DOS Russian                 | cp866_general_ci    |      1 |</div><div class="line">| keybcs2  | DOS Kamenicky Czech-Slovak  | keybcs2_general_ci  |      1 |</div><div class="line">| macce    | Mac Central European        | macce_general_ci    |      1 |</div><div class="line">| macroman | Mac West European           | macroman_general_ci |      1 |</div><div class="line">| cp852    | DOS Central European        | cp852_general_ci    |      1 |</div><div class="line">| latin7   | ISO 8859-13 Baltic          | latin7_general_ci   |      1 |</div><div class="line">| utf8mb4  | UTF-8 Unicode               | utf8mb4_general_ci  |      4 |</div><div class="line">| cp1251   | Windows Cyrillic            | cp1251_general_ci   |      1 |</div><div class="line">| utf16    | UTF-16 Unicode              | utf16_general_ci    |      4 |</div><div class="line">| utf16le  | UTF-16LE Unicode            | utf16le_general_ci  |      4 |</div><div class="line">| cp1256   | Windows Arabic              | cp1256_general_ci   |      1 |</div><div class="line">| cp1257   | Windows Baltic              | cp1257_general_ci   |      1 |</div><div class="line">| utf32    | UTF-32 Unicode              | utf32_general_ci    |      4 |</div><div class="line">| binary   | Binary pseudo charset       | binary              |      1 |</div><div class="line">| geostd8  | GEOSTD8 Georgian            | geostd8_general_ci  |      1 |</div><div class="line">| cp932    | SJIS for Windows Japanese   | cp932_japanese_ci   |      2 |</div><div class="line">| eucjpms  | UJIS for Windows Japanese   | eucjpms_japanese_ci |      3 |</div><div class="line">+----------+-----------------------------+---------------------+--------+</div><div class="line">40 rows in set (0.01 sec)</div></pre></td></tr></table></figure>
<h4 id="校对集"><a href="#校对集" class="headerlink" title="校对集"></a>校对集</h4><p>在某种特定的字符集下，字符和字符的大小关系。比如a和B的大小关系：如果不区分大小写a<b；如果区分大小写a>B。<br>脚下留心：不同的校对集他们的比较结果是不一样的<br>语法：<code>collate=校对集</code><br>创建两个表</b；如果区分大小写a></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line">create table stu1(</div><div class="line">name varchar(20)</div><div class="line">)charset=utf8 collate=utf8_general_ci;</div><div class="line"></div><div class="line">create table stu2(</div><div class="line">name varchar(20)</div><div class="line">)charset=utf8 collate=utf8_bin;</div><div class="line">–插入测试数据</div><div class="line">insert into stu1 values (&apos;a&apos;),(&apos;B&apos;);</div><div class="line">insert into stu2 values (&apos;a&apos;),(&apos;B&apos;);</div></pre></td></tr></table></figure>
<p>测试</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div></pre></td><td class="code"><pre><div class="line">mysql&gt; select * from stu1 order by name;</div><div class="line">+------+</div><div class="line">| name |</div><div class="line">+------+</div><div class="line">| a    |</div><div class="line">| B    |</div><div class="line">+------+</div><div class="line">2 rows in set (0.01 sec)</div><div class="line"></div><div class="line">mysql&gt; select * from stu2 order by name;</div><div class="line">+------+</div><div class="line">| name |</div><div class="line">+------+</div><div class="line">| B    |</div><div class="line">| a    |</div><div class="line">+------+</div><div class="line">2 rows in set (0.00 sec)</div></pre></td></tr></table></figure>
<p>校对集的规则：<br>1、_bin:按二进制编码进行比较<br>2、_ci:不区分大小写进行比较</p>
<p><strong>查看所有的校对集</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div></pre></td><td class="code"><pre><div class="line">mysql&gt; show collation;</div><div class="line">+--------------------------+----------+-----+---------+----------+---------+</div><div class="line">| Collation                | Charset  | Id  | Default | Compiled | Sortlen |</div><div class="line">+--------------------------+----------+-----+---------+----------+---------+</div><div class="line">| big5_chinese_ci          | big5     |   1 | Yes     | Yes      |       1 |</div><div class="line">| big5_bin                 | big5     |  84 |         | Yes      |       1 |</div><div class="line">| dec8_swedish_ci          | dec8     |   3 | Yes     | Yes      |       1 |</div><div class="line">| dec8_bin                 | dec8     |  69 |         | Yes      |       1 |</div><div class="line"></div><div class="line">此处省略200多行...</div></pre></td></tr></table></figure>
<p><a href="http://oamgu5mjf.bkt.clouddn.com/%E6%95%B0%E6%8D%AE%E5%BA%93%E6%93%8D%E4%BD%9C.docx" target="_blank" rel="external">常用操作命令文件下载</a></p>

          
        
      
    </div>

    <div>
      
    </div>

    <div>
      
    </div>

    <footer class="post-footer">
      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </article>


    
      

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                
                <a class="post-title-link" href="/20160828-1.html" itemprop="url">
                  php数组比较-usort
                </a>
              
            
          </h1>
        

        <div class="post-meta">
        
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">发表于</span>
            <time itemprop="dateCreated" datetime="2016-08-28T16:07:47+08:00" content="2016-08-28">
              2016-08-28
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/PHP/" itemprop="url" rel="index">
                    <span itemprop="name">PHP</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/20160828-1.html#comments" itemprop="discussionUrl">
                  <span class="post-comments-count ds-thread-count" data-thread-key="20160828-1.html" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          

          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <h3 id="usort-、getdate"><a href="#usort-、getdate" class="headerlink" title="usort()、getdate()"></a>usort()、getdate()</h3><p>自定义排序，书写一个函数，对数组里面的元素大小两两进行比较，如果return -1，则将大的放在前面，如果return 1，则将大的放在后面。</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div><div class="line">20</div><div class="line">21</div></pre></td><td class="code"><pre><div class="line"><span class="meta">&lt;?php</span> </div><div class="line">$arr5 = <span class="keyword">array</span>(</div><div class="line">		<span class="keyword">array</span>(<span class="string">'name'</span>=&gt;<span class="string">'jack'</span>,<span class="string">'age'</span>=&gt;<span class="number">24</span>,<span class="string">'sex'</span>=&gt;<span class="string">'man'</span>),</div><div class="line">		<span class="keyword">array</span>(<span class="string">'name'</span>=&gt;<span class="string">'rose'</span>,<span class="string">'age'</span>=&gt;<span class="number">38</span>,<span class="string">'sex'</span>=&gt;<span class="string">'wom'</span>),</div><div class="line">		<span class="keyword">array</span>(<span class="string">'name'</span>=&gt;<span class="string">'lucy'</span>,<span class="string">'age'</span>=&gt;<span class="number">16</span>,<span class="string">'sex'</span>=&gt;<span class="string">'girl'</span>),</div><div class="line">		<span class="keyword">array</span>(<span class="string">'name'</span>=&gt;<span class="string">'lili'</span>,<span class="string">'age'</span>=&gt;<span class="number">19</span>,<span class="string">'sex'</span>=&gt;<span class="string">'girl'</span>),</div><div class="line">		<span class="keyword">array</span>(<span class="string">'name'</span>=&gt;<span class="string">'Tomi'</span>,<span class="string">'age'</span>=&gt;<span class="number">27</span>,<span class="string">'sex'</span>=&gt;<span class="string">'boy'</span>)</div><div class="line">	);</div><div class="line"></div><div class="line">usort($arr5,<span class="function"><span class="keyword">function</span><span class="params">($num1,$num2)</span></span>&#123;</div><div class="line">	<span class="keyword">if</span> ($num1[<span class="string">'age'</span>]==$num2[<span class="string">'age'</span>]) &#123;</div><div class="line">		<span class="keyword">return</span> <span class="number">0</span>;</div><div class="line">	&#125;</div><div class="line">	<span class="keyword">return</span> ($num1[<span class="string">'age'</span>]&gt;$num2[<span class="string">'age'</span>] ? <span class="number">1</span> : <span class="number">-1</span>);</div><div class="line">&#125;);</div><div class="line"></div><div class="line"><span class="keyword">echo</span> <span class="string">"&lt;pre&gt;"</span>;</div><div class="line">var_dump($arr5);</div><div class="line"><span class="keyword">echo</span> <span class="string">"&lt;/pre&gt;"</span>;</div><div class="line"></div><div class="line"> <span class="meta">?&gt;</span></div></pre></td></tr></table></figure>
<blockquote>
<p>将二维数组按年龄进行排序</p>
</blockquote>
<p>计算上月最后一天星期几</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div></pre></td><td class="code"><pre><div class="line">//方法一：玩转一周7天</div><div class="line">$t = time();</div><div class="line">$today = date(&apos;d&apos;,$t);//28</div><div class="line">$weekday = localtime(time(),true);//时间数组</div><div class="line">$week = $weekday[&apos;tm_wday&apos;];//今天星期几</div><div class="line">$res = ($today + $week)%7; //本月已过的天数+星期取7的余数就是上月最后一天</div><div class="line">echo &apos;上月最后一天星期：&apos;.$res;</div><div class="line"></div><div class="line">echo &quot;&lt;hr&gt;&quot;;</div><div class="line"></div><div class="line">//方法二：玩转时间戳</div><div class="line">$today = getdate(time())[&apos;mday&apos;];</div><div class="line">$today2 = $today*24*60*60*1000;</div><div class="line">$today1 = time();</div><div class="line">$diff = $today1 - $today2;</div><div class="line">$res2 = getdate($diff);</div><div class="line">echo &apos;上月最后一天星期：&apos;.$res2[&apos;wday&apos;];</div></pre></td></tr></table></figure>
<p>补充小知识：</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div></pre></td><td class="code"><pre><div class="line">getdate()[0] == time();</div><div class="line">getdate(time())[&apos;mday&apos;] == date(&apos;d&apos;,time());</div></pre></td></tr></table></figure>
<p>获取当前页面编码：<code>mb_internal_encoding()</code><br>修改当前页面编码：<code>mb_interval_encoding(utf-8)</code></p>

          
        
      
    </div>

    <div>
      
    </div>

    <div>
      
    </div>

    <footer class="post-footer">
      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </article>


    
      

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                
                <a class="post-title-link" href="/20160827-1.html" itemprop="url">
                  Day6-php数组、字符串
                </a>
              
            
          </h1>
        

        <div class="post-meta">
        
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">发表于</span>
            <time itemprop="dateCreated" datetime="2016-08-27T17:18:51+08:00" content="2016-08-27">
              2016-08-27
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/PHP/" itemprop="url" rel="index">
                    <span itemprop="name">PHP</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/20160827-1.html#comments" itemprop="discussionUrl">
                  <span class="post-comments-count ds-thread-count" data-thread-key="20160827-1.html" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          

          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <p><strong>本章是需要熟记的函数，使用的时候有问题查手册</strong></p>
<h3 id="操作数组的函数"><a href="#操作数组的函数" class="headerlink" title="操作数组的函数"></a>操作数组的函数</h3><h4 id="is-array"><a href="#is-array" class="headerlink" title="is_array()"></a>is_array()</h4><p>判断一个变量是否是一个数组，返回是一个布尔型，如果是数组返回真，如果不是数组，返回假</p>
<h4 id="array-search"><a href="#array-search" class="headerlink" title="array_search()"></a>array_search()</h4><p>查找一个值是否正在一个数组中，返回的是以键名<br>语法：<code>$arr = array_search(&#39;3&#39;,$arr);</code></p>
<blockquote>
<p>array_search()查找值区分大小写，不区分数据类型，如果出现同值问题，取前面第一个下标。<br>第三个参数如果是true则区分数据类型<code>$arr = array_search(&#39;3&#39;,$arr,true);</code></p>
</blockquote>
<h3 id="操作键值的函数"><a href="#操作键值的函数" class="headerlink" title="操作键值的函数"></a>操作键值的函数</h3><h4 id="array-keys"><a href="#array-keys" class="headerlink" title="array_keys()"></a>array_keys()</h4><p>获取数组中的所有下标，以一个索引数组的模式返回<br>语法：<code>$arr2 = array_keys($arr);</code></p>
<blockquote>
<p>获取的数组，下标从0开始依次递增</p>
</blockquote>
<h4 id="array-values"><a href="#array-values" class="headerlink" title="array_values()"></a>array_values()</h4><p>获取数组中的所有值，以一个索引数组的模式返回<br>语法：<code>$arr3 = array_values($arr);</code></p>
<blockquote>
<p>如果值是一个数组，也同样将这个数组当成以值赋值给数组</p>
</blockquote>
<h4 id="array-combine"><a href="#array-combine" class="headerlink" title="array_combine()"></a>array_combine()</h4><p>将两个数组的值合并成一个数组，第一个数组是下标，第二个数组是值<br>语法：<code>$arr4 = array_combine($arr1,$arr2);</code></p>
<blockquote>
<p>返回的数据类型是一个数组。两个数组参数的元素个数必须要一一对应</p>
</blockquote>
<h4 id="in-array"><a href="#in-array" class="headerlink" title="in_array()"></a>in_array()</h4><p>查找数组中的某一个值是否存在<br>语法：<code>var_dump(in_array(&#39;a&#39;,$arr));</code></p>
<blockquote>
<p>in_array查找是区分大小写的，并且默认不区分数据类型，如果想让他区分数据类型，将第三个参数修改为true即可；<br>第一个参数是需要查找的值，第二个参数是查找的数组，返回的结果是一个布尔值<br>而array_search返回的是一个键名</p>
</blockquote>
<h4 id="array-key-exists"><a href="#array-key-exists" class="headerlink" title="array_key_exists()"></a>array_key_exists()</h4><p>查找一个键是否在某个数组中<br>语法：<code>var_dump(array_key_exists(&#39;1&#39;,$arr));</code></p>
<blockquote>
<p>第一个参数是需要查找的下标，第二个参数是需要寻找的数组，返回的结果是一个boolean型<br>本身就不区分数据类型，没有第三个参数；</p>
</blockquote>
<h4 id="isset"><a href="#isset" class="headerlink" title="isset()"></a>isset()</h4><p>判断一个变量是否已经被定义，如果没有被定义或者值为null返回的结果是false<br>语法：<code>var_dump(isset($arr[&#39;b&#39;]));</code></p>
<blockquote>
<p>isset()和array_key_exists的区别，如果下标对应的值为空。isset返回的结果是false，array_key_exists返回的结果是true</p>
</blockquote>
<h3 id="合并和拆分字符、数组的函数"><a href="#合并和拆分字符、数组的函数" class="headerlink" title="合并和拆分字符、数组的函数"></a>合并和拆分字符、数组的函数</h3><h4 id="implode"><a href="#implode" class="headerlink" title="implode()"></a>implode()</h4><p>将一个数组里面的元素合并成一个字符串<br>语法：<code>$str = implode(&#39;&#39;,$arr);</code></p>
<blockquote>
<p>两个参数，第一个是元素值和值之间连接的符号（第一个可以不写），第二个参数是你需要遍历的数组。join()就是implode别名函数</p>
</blockquote>
<h4 id="explode"><a href="#explode" class="headerlink" title="explode()"></a>explode()</h4><p>将一个字符串拆分成一个数组<br>语法：<code>$arr = explode(&#39;a&#39;,$str);</code></p>
<blockquote>
<p>两个参数，第一个是拆分字符串的标志，第二个参数是需要拆分的字符串</p>
</blockquote>
<p>语法：<code>$arr = explode(&#39;a&#39;,$str,3);</code></p>
<blockquote>
<p>如果第三个元素是正整数，分割成三个部分，最后一个元素会将包含剩下的所有的包含<br>如果第三个原始是负整数，则会将最后的3个元素抛弃，</p>
</blockquote>
<h3 id="数组的交并差"><a href="#数组的交并差" class="headerlink" title="数组的交并差"></a>数组的交并差</h3><h4 id="array-merge"><a href="#array-merge" class="headerlink" title="array_merge()"></a>array_merge()</h4><p>合并两个数组：array_merge(数组1,数组2)<br>语法：<code>$arr = array_merge(range(0,9),range(&#39;a&#39;,&#39;z&#39;));</code></p>
<blockquote>
<p>array_merge如果合并两个数字下标的数组，会将数字重新从0进行组合。<br>array_merge如果合并两个字符串下标的数组，后面的值会将前面的值覆盖。<br>array_merge合并两个数组，先从第一个数组开始合并，然后在合并第二个数组。</p>
</blockquote>
<h4 id="array-diff"><a href="#array-diff" class="headerlink" title="array_diff()"></a>array_diff()</h4><p>计算数组差值<br>语法：<code>array array_diff ( array $array1 , array $array2 [, array $... ] )</code></p>
<blockquote>
<p>对比返回在 array1 中但是不在 array2 及任何其它参数数组中的值。<br>返回一个数组，该数组包括了所有在 array1 中但是不在任何其它参数数组中的值。注意键名保留不变</p>
</blockquote>
<h4 id="array-intersect"><a href="#array-intersect" class="headerlink" title="array_intersect()"></a>array_intersect()</h4><p>计算数组的交集<br>语法：<code>array array_intersect ( array $array1 , array $array2 [, array $ ... ] )</code></p>
<blockquote>
<p>array_intersect() 返回一个数组，该数组包含了所有在 array1 中也同时出现在所有其它参数数组中的值。注意键名保留不变。</p>
</blockquote>
<h3 id="函数遍历数组"><a href="#函数遍历数组" class="headerlink" title="函数遍历数组"></a>函数遍历数组</h3><p>回调函数是由计算机自己去调用php中的函数</p>
<h4 id="array-map"><a href="#array-map" class="headerlink" title="array_map()"></a>array_map()</h4><p>将回调函数作用到给定数组的单元上<br>语法：<code>array array_map ( callable $callback , array $arr1 [, array $... ] )</code><br>语法： array_map(‘函数名’,数组名)。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">//使用系统函数，调用数组</div><div class="line">$arr=array(10,-12,46,-9,-45);</div><div class="line">$arr2 = array_map(&apos;abs&apos;,$arr);</div><div class="line">var_dump($arr2);</div></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">//使用自身定义的函数，调用数组</div><div class="line">$arr=array(10,-12,46,-9,-45);</div><div class="line">fucntion fn($num)&#123;</div><div class="line">	$num+=10;</div><div class="line">	return $num;</div><div class="line">&#125;</div><div class="line">$arr2 = array_map(&apos;fn&apos;,$arr);</div><div class="line">var_dump($arr2);</div></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">//使用匿名函数，调用数组</div><div class="line">$arr=array(10,-12,46,-9,-45);</div><div class="line">$arr2 = array_map(function($name)&#123;return &apos;hello&apos;.$name;&#125;,$arr);</div><div class="line">var_dump($arr2);</div></pre></td></tr></table></figure>
<blockquote>
<p>结果将所有数字转换为正数；</p>
<ol>
<li><code>array_map()</code>返回一个数组，该数组包含了 arr1 中的所有单元经过 callback 作用过之后的单元。callback 接受的参数数目应该和传递给 array_map() 函数的数组数目一致。</li>
<li>array_map去回调我们自己定义好的函数</li>
<li>除了第一个参数直接写函数名的方法以外，我们也可以直接写一个匿名函数，达到回调函数的功能</li>
<li>如果第一个参数的值为null，则会把后面的数组的每一个值取出来进行拼接，合并成一个新的数组</li>
</ol>
</blockquote>
<h4 id="array-walk"><a href="#array-walk" class="headerlink" title="array_walk()"></a>array_walk()</h4><p>功能类似于遍历数组，可以同时获取数组里面的值和下标</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">$arr = array(&apos;name&apos;=&gt;&apos;张无忌&apos;,&apos;age&apos;=&gt;528,&apos;sex&apos;=&apos;男&apos;);</div><div class="line">function fn($value,$key)&#123;</div><div class="line">	echo $key.&apos;-&apos;.$value.&apos;&lt;br&gt;&apos;;</div><div class="line">&#125;</div><div class="line">$arr2 = array_walk($arr,&apos;fn&apos;);</div></pre></td></tr></table></figure>
<p>可以分别获取下标和值，进行计算。如果函数只写一个参数，则获取的是数组里面的值。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div></pre></td><td class="code"><pre><div class="line">$arr2 = array_walk($arr,function($value,$key)&#123;</div><div class="line">	echo $key.&apos;-&gt;&apos;.$value,&apos;&lt;br&gt;&apos;;</div><div class="line">&#125;)</div></pre></td></tr></table></figure>
<blockquote>
<p>array_walk同样支持匿名函数的用法</p>
</blockquote>
<ul>
<li><p>接触最多的回调函数还是<code>array_map()，array_walk()</code>用的次数相对于而言，比较少。</p>
</li>
<li><p>array_walk第一个参数写的数组名，第二个参数写的才是调用的数组<br>array_walk返回的结果只会是一个布尔型的结果，如果array_walk执行成功返回的记过就是true，如果array_walk执行失败，返回的救过就是false，他不会生成一个新的数组；</p>
</li>
</ul>
<h3 id="栈和队列"><a href="#栈和队列" class="headerlink" title="栈和队列"></a>栈和队列</h3><p>栈的特点就是先进后出，后进先出。<br>队列的特点就是先进先出，后进后出。</p>
<h4 id="array-push"><a href="#array-push" class="headerlink" title="array_push()"></a>array_push()</h4><p>第一个参数是需要放置的数组，后面的参数是需要放置的元素</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">$arr = array();</div><div class="line">array_push($arr,&apos;a&apos;);</div><div class="line">array_push($arr,&apos;b&apos;,&apos;c&apos;,&apos;d&apos;);</div><div class="line">print_r($arr);</div></pre></td></tr></table></figure>
<blockquote>
<p>一次性可以放置多个元素</p>
</blockquote>
<h4 id="array-pop"><a href="#array-pop" class="headerlink" title="array_pop()"></a>array_pop()</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">$arr = array();</div><div class="line">array_push($arr,&apos;a&apos;);</div><div class="line">array_push($arr,&apos;b&apos;,&apos;c&apos;,&apos;d&apos;);</div><div class="line">array_pop($arr);</div><div class="line">array_pop($arr);</div><div class="line">print_r($arr);</div></pre></td></tr></table></figure>
<blockquote>
<p>出栈一次只能出一个元素。d和c后进的元素，先被拿出来了</p>
</blockquote>
<p>返回结果：mexd,溢出的元素</p>
<h4 id="array-shift"><a href="#array-shift" class="headerlink" title="array_shift()"></a>array_shift()</h4><p>出队列</p>
<blockquote>
<p>思考：unset和arr_shift有什么区别？<br>答案：使用array_shift去移除一个元素，那个其他的元素位置会往前移一位，保持数据完整性；但是unset删除一个元素，下标也会被删除</p>
</blockquote>
<h4 id="array-unshift"><a href="#array-unshift" class="headerlink" title="array_unshift()"></a>array_unshift()</h4><p>就是在数组的第一个位置插入一个元素。</p>
<blockquote>
<p>往数组里面第一个元素的位置放置一个元素。</p>
<p>栈和队列的优点：栈和队列都是有效保证数据的完整性；</p>
</blockquote>
<h3 id="数组的排序"><a href="#数组的排序" class="headerlink" title="数组的排序"></a>数组的排序</h3><h4 id="sort"><a href="#sort" class="headerlink" title="sort()"></a>sort()</h4><p>按照数值值得大小进行排序。从小到大的顺序</p>
<blockquote>
<p>将原有的下标丢弃，从0开始依次递增</p>
</blockquote>
<h4 id="rsort"><a href="#rsort" class="headerlink" title="rsort()"></a>rsort()</h4><p>按照数组的数值进行排序，从大到小的顺序。</p>
<blockquote>
<p>也是将原有的下标丢弃，从0开始依次递增</p>
</blockquote>
<h4 id="asort"><a href="#asort" class="headerlink" title="asort()"></a>asort()</h4><p>按照数组的数值进行排序，从小到大排序，但是会保留下标</p>
<h4 id="arsort"><a href="#arsort" class="headerlink" title="arsort()"></a>arsort()</h4><p>按照数组的数值进行排序，从大到小排序，但是会保留下标</p>
<h4 id="ksort"><a href="#ksort" class="headerlink" title="ksort()"></a>ksort()</h4><p>按照数组的下标顺序进行排序。从小到大进行排序</p>
<h4 id="krsort"><a href="#krsort" class="headerlink" title="krsort()"></a>krsort()</h4><p>按照数组的下标顺序进行排序，从大到小进行排序</p>
<h4 id="natsort"><a href="#natsort" class="headerlink" title="natsort()"></a>natsort()</h4><p>自然排序</p>
<blockquote>
<p>将字符串整体进行排序，而sort会挨个字符进行比较，然后进行排序</p>
</blockquote>
<h4 id="usort"><a href="#usort" class="headerlink" title="usort()"></a>usort()</h4><p>自定义排序</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div><div class="line">10</div><div class="line">11</div><div class="line">12</div><div class="line">13</div><div class="line">14</div><div class="line">15</div><div class="line">16</div><div class="line">17</div><div class="line">18</div><div class="line">19</div></pre></td><td class="code"><pre><div class="line">$arr = array(</div><div class="line">	array(&apos;name&apos;=&gt;&apos;jack&apos;,&apos;math&apos;=&gt;78,&apos;age&apos;=&gt;56),</div><div class="line">	array(&apos;name&apos;=&gt;&apos;rose&apos;,&apos;math&apos;=&gt;98,&apos;age&apos;=&gt;14),</div><div class="line">	array(&apos;name&apos;=&gt;&apos;jame&apos;,&apos;math&apos;=&gt;56,&apos;age&apos;=&gt;67),</div><div class="line">	array(&apos;name&apos;=&gt;&apos;uiste&apos;,&apos;math&apos;=&gt;45,&apos;age&apos;=&gt;24)</div><div class="line">	);</div><div class="line">usort($arr,function($num1,$num2)&#123;</div><div class="line">	if ($num1[&apos;age&apos;]&gt;$num2[&apos;age&apos;]) &#123;</div><div class="line">		return 1;</div><div class="line">	&#125;elseif ($num1[&apos;age&apos;]&lt;$num2[&apos;age&apos;]) &#123;</div><div class="line">		return -1;</div><div class="line">	&#125;else&#123;</div><div class="line">		return 0;</div><div class="line">	&#125;</div><div class="line">&#125;);</div><div class="line"></div><div class="line">echo &quot;&lt;pre&gt;&quot;;</div><div class="line">print_r($arr);</div><div class="line">echo &quot;&lt;/pre&gt;&quot;;</div></pre></td></tr></table></figure>
<blockquote>
<p>在第一个参数小于，等于或大于第二个参数时，该比较函数必须相应地返回一个小于，等于或大于0的整数。</p>
</blockquote>
<p>如果return -1则值放在前面<br>如果 return 1 则值放在后面<br>如果 return 0 则值的位置不发生变化</p>
<h3 id="关于字符串的函数"><a href="#关于字符串的函数" class="headerlink" title="关于字符串的函数"></a>关于字符串的函数</h3><h4 id=""><a href="#" class="headerlink" title="[]"></a>[]</h4><p>字符串可以理解成字符的合计。</p>
<blockquote>
<p>所以，[]就是获取字符串中的某一个字符</p>
</blockquote>
<h4 id="strlen"><a href="#strlen" class="headerlink" title="strlen()"></a>strlen()</h4><p>获取字符串的长度</p>
<blockquote>
<p>获取长度的单位是字节,中文下的感叹号也被分解为三个字节；空格也在空间</p>
</blockquote>
<h4 id="trim"><a href="#trim" class="headerlink" title="trim()"></a>trim()</h4><p>去除两边的空格</p>
<h4 id="rtrim"><a href="#rtrim" class="headerlink" title="rtrim()"></a>rtrim()</h4><p>除去右边的空格</p>
<h4 id="ltrim"><a href="#ltrim" class="headerlink" title="ltrim()"></a>ltrim()</h4><p>去除左边的空格</p>
<h4 id="strpos"><a href="#strpos" class="headerlink" title="strpos()"></a>strpos()</h4><p>获取字符串某个字符的位置<br>语法：<code>strpos($str,&#39;b&#39;);</code></p>
<blockquote>
<p>获取某个字符首次出现的位置。如果后面加上第三个参数，代表字符串从某个位置开始往后去寻找。如果没写第三个参数，则第三个参数默认为0</p>
</blockquote>
<p>语法：<code>strpos($str,&#39;b&#39;,3);</code></p>
<blockquote>
<p>参数为3，则是从字符串第4个位置开始去寻找</p>
</blockquote>
<h4 id="strrpos"><a href="#strrpos" class="headerlink" title="strrpos()"></a>strrpos()</h4><p>获取某个字符出现的最后一个位置<br>语法：<code>var_dump(strrpo($str,&#39;b&#39;,2));</code></p>
<blockquote>
<p>从右往左查找，第三个参数代表最终查找到某个字符结束。找到返回下标，找不到返回false;</p>
</blockquote>
<h4 id="str-repeat"><a href="#str-repeat" class="headerlink" title="str_repeat()"></a>str_repeat()</h4><p>将某个字符串重复多少次</p>
<blockquote>
<p>第一个参数是需要重复的字符串，第二个参数重复的次数；</p>
</blockquote>
<h4 id="chr"><a href="#chr" class="headerlink" title="chr()"></a>chr()</h4><p>将一个数字转换成ASCII码</p>
<h4 id="ord"><a href="#ord" class="headerlink" title="ord()"></a>ord()</h4><p>将一个ASCII转换成对应的数字</p>
<h4 id="substr"><a href="#substr" class="headerlink" title="substr()"></a>substr()</h4><p>截取某个字符串<br>语法：<code>substr($str,3);</code></p>
<blockquote>
<p>从下标为3的字符开始，一直截取到结束</p>
</blockquote>
<p>语法：<code>substr($str,3,4);</code></p>
<blockquote>
<p>从下标为3的字符开始，截取4个字符</p>
</blockquote>
<p>语法：<code>substr($str,3,-3);</code></p>
<blockquote>
<p>从下标为3的字符开始截取，舍去最后三个字符</p>
</blockquote>
<p>语法：<code>substr($str,-4,2);</code></p>
<blockquote>
<p>从右往左数4个字符开始截取，截取2个</p>
</blockquote>
<p>语法：<code>substr($str,-5,-2);</code></p>
<blockquote>
<p>从右往左数第五个字符开始截取，截取到倒数第二位终止</p>
</blockquote>
<h4 id="strchr"><a href="#strchr" class="headerlink" title="strchr()"></a>strchr()</h4><p>从某个字符开始截取<br>语法：<code>strchr($str,&#39;c&#39;);</code></p>
<blockquote>
<p>从左往右第一个c开始截取到最后（区分大小写）</p>
<p>strstr()的功能和strchr()的功能一模一样，只不过名称不同</p>
</blockquote>
<h4 id="stristr"><a href="#stristr" class="headerlink" title="stristr()"></a>stristr()</h4><p>也是从某个字符开始截取，但是不区分大小写</p>
<h4 id="strrchr"><a href="#strrchr" class="headerlink" title="strrchr()"></a>strrchr()</h4><p>从某个字符最后出现的位置开始往后截取</p>
<blockquote>
<p>可以非常方便的获取文件的后缀名</p>
</blockquote>
<h4 id="str-replace"><a href="#str-replace" class="headerlink" title="str_replace()"></a>str_replace()</h4><p>语法：<code>str_replace(替换前的字符串，替换后的字符串，需要替换的字符串)</code></p>
<h4 id="str-split"><a href="#str-split" class="headerlink" title="str_split()"></a>str_split()</h4><p>分割字符串，生成一个数组</p>
<blockquote>
<p>第一个参数是一个字符串，第二个参数代表以几个字节进行拆分<br>explode是以字符进行拆分的</p>
</blockquote>
<h4 id="str-pad"><a href="#str-pad" class="headerlink" title="str_pad()"></a>str_pad()</h4><p>填充字符串</p>
<blockquote>
<p>四个参数组成，第一个是填充的字符串，第二个是长度，第三个是填充物，第四个是左，右，两边填充</p>
</blockquote>
<h4 id="strtolower"><a href="#strtolower" class="headerlink" title="strtolower()"></a>strtolower()</h4><p>将一个字符串转换成全小写</p>
<h4 id="strtoupper"><a href="#strtoupper" class="headerlink" title="strtoupper()"></a>strtoupper()</h4><p>将一个字符串转换成全大写</p>
<h4 id="nl2br"><a href="#nl2br" class="headerlink" title="nl2br()"></a>nl2br()</h4><p>将\n转换成<br></p>
<h4 id="htmlspecialchars"><a href="#htmlspecialchars" class="headerlink" title="htmlspecialchars():"></a>htmlspecialchars():</h4><p>将标签当成普通文本输出</p>
<h4 id="urlencode"><a href="#urlencode" class="headerlink" title="urlencode()"></a>urlencode()</h4><p>可以将字符串进行加密</p>
<h4 id="urldecode"><a href="#urldecode" class="headerlink" title="urldecode()"></a>urldecode()</h4><p>可以将加密好的字符串进行解码</p>
<h3 id="多字符处理函数"><a href="#多字符处理函数" class="headerlink" title="多字符处理函数"></a>多字符处理函数</h3><p>多字符处理函数，不是php默认的开启模式，需要通过配置php.ini进行操作</p>
<blockquote>
<p>extension=php_mbstring.dll</p>
</blockquote>
<h4 id="mb-strlen"><a href="#mb-strlen" class="headerlink" title="mb_strlen()"></a>mb_strlen()</h4><p>获取字符的长度</p>
<blockquote>
<p>第一个参数是我们需要获取的字符串，第二个参数是选择的编码格式</p>
</blockquote>
<h4 id="mb-internal-encoding"><a href="#mb-internal-encoding" class="headerlink" title="mb_internal_encoding()"></a>mb_internal_encoding()</h4><ul>
<li>获取当前的编码格式（不加参数）</li>
<li>修改当前的编码模式（增加参数）</li>
</ul>
<h4 id="mb-strpos"><a href="#mb-strpos" class="headerlink" title="mb_strpos()"></a>mb_strpos()</h4><p>查找当前某个字符的位置</p>
<h4 id="mb-substr"><a href="#mb-substr" class="headerlink" title="mb_substr()"></a>mb_substr()</h4><p>截取字符</p>
<h4 id="iconv"><a href="#iconv" class="headerlink" title="iconv()"></a>iconv()</h4><p>转换格式</p>
<blockquote>
<p>里面三个参数，第一个是当前的编码，第二个是转换后的编码，第三个是需要转换的字符串</p>
</blockquote>

          
        
      
    </div>

    <div>
      
    </div>

    <div>
      
    </div>

    <footer class="post-footer">
      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </article>


    
      

  
  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">
            
            
              
                
                <a class="post-title-link" href="/20160826-1.html" itemprop="url">
                  Day5-php数组相关
                </a>
              
            
          </h1>
        

        <div class="post-meta">
        
          <span class="post-time">
            <span class="post-meta-item-icon">
              <i class="fa fa-calendar-o"></i>
            </span>
            <span class="post-meta-item-text">发表于</span>
            <time itemprop="dateCreated" datetime="2016-08-26T17:18:51+08:00" content="2016-08-26">
              2016-08-26
            </time>
          </span>

          
            <span class="post-category" >
              &nbsp; | &nbsp;
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
              
                <span itemprop="about" itemscope itemtype="https://schema.org/Thing">
                  <a href="/categories/PHP/" itemprop="url" rel="index">
                    <span itemprop="name">PHP</span>
                  </a>
                </span>

                
                

              
            </span>
          

          
            
              <span class="post-comments-count">
                &nbsp; | &nbsp;
                <a href="/20160826-1.html#comments" itemprop="discussionUrl">
                  <span class="post-comments-count ds-thread-count" data-thread-key="20160826-1.html" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          

          
          

          
        </div>
      </header>
    


    <div class="post-body" itemprop="articleBody">

      
      

      
        
          
            <blockquote>
<p>复习：<br>匿名函数use用法：将外部和匿名函数处于同一级的变量引用到匿名函数的内部，引用的变量和外部的变量是一个值传递的关系。如果需要引用传址，则在usb变量前加&amp;符号</p>
</blockquote>
<h3 id="迭代"><a href="#迭代" class="headerlink" title="迭代"></a>迭代</h3><blockquote>
<p>单单从思想的角度上看，递归和迭代没有谁优谁劣，都是一样的，就和大家偏文科偏理科一样，但是，从代码的角度上来看，无疑是迭代的思想更加具有效率，所以建议大家以后去多用迭代的思想去解决问题。</p>
</blockquote>
<h3 id="数组"><a href="#数组" class="headerlink" title="数组"></a>数组</h3><p>不是所有关联数组都是字符串下标<br><code>$arr = array(1110=&gt;&#39;刘德华&#39;,1111=&gt;&#39;金城武&#39;);</code><br>不是所有数组都是整形下标<br><code>$arr = array(&#39;a&#39;=&gt;&#39;雪碧&#39;,&#39;b&#39;=&gt;&#39;可乐&#39;,&#39;c&#39;=&gt;&#39;王老吉&#39;);</code></p>
<h4 id="foreach-遍历数组"><a href="#foreach-遍历数组" class="headerlink" title="foreach 遍历数组"></a>foreach 遍历数组</h4><p>语法：<br><code>foreach(需要遍历数组的名称 as 数组的键 =&gt; 数组的值){  }</code></p>
<p>语法：<br><code>foreach(需要遍历数组的名称 as  数组的值){  }</code></p>
<p>注意：</p>
<blockquote>
<p>foreach遍历数组的时候，数组的指针会自动的下移。<br>foreach遍历完数组以后，指针会指向一个非法的位置<br>foreach在遍历数组之前，会现对数组做一个初始化的操作</p>
</blockquote>
<p>foreach遍历数组，实际是遍历数组的拷贝值,改变原数组的结果，不会影响到遍历数组的结果,foreach遍历数组，如果改变$value的值，原数组不会发生变化</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">foreach($arr as $key =&gt; $value)&#123;</div><div class="line">	$value = &apos;加多宝&apos;;</div><div class="line">	echo &apos;数组的下标是：&apos;.$key.&apos;&lt;br&gt;&apos;;</div><div class="line">	echo &apos;数组的值为：&apos;.$value.&apos;&lt;br&gt;&apos;;</div><div class="line">&#125;</div><div class="line">var_dump($arr);</div></pre></td></tr></table></figure>
<p>foreach遍历数组同样支持引用传值，改变$value的值，原数组也会随之发生变化。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">foreach($arr as &amp;$value)&#123;</div><div class="line">	$value = &apos;加多宝&apos;;</div><div class="line">	echo &apos;数组的值为：&apos;.$value.&apos;&lt;br&gt;&apos;;</div><div class="line">&#125;</div><div class="line">var_dump($arr);</div></pre></td></tr></table></figure>
<blockquote>
<p>foreach遍历完数组以后，下标是一个不确定的情况，如果foreach遍历完以后需要使用数组，最好将他做一个初始化的操作。</p>
</blockquote>
<h4 id="指针-遍历数组"><a href="#指针-遍历数组" class="headerlink" title="指针 遍历数组"></a>指针 遍历数组</h4><blockquote>
<p>通过移动数组的指针，完成一个遍历数组的情况，指针指向的位置一般是分为一个合法位和非法位</p>
</blockquote>
<p>next($arr) :   让指针下移一位–&gt;指针下移<br>current($arr):  获取指针指向当前元素的值–&gt;获取当前值<br>key($arr)  :   获取指针指向当前元素的下标–&gt;获取当前元素下标</p>
<p>for(;current($arr);next($arr)){<br>    echo “数组元素的下标为：”.key($arr).’<br>‘;<br>    echo “数组元素的值为：”.current($arr).’<br>‘;<br>}</p>
<p>prev()        :    让数组的指针上移一位。</p>
<blockquote>
<p>上移指针和下移指针是相对于现在的位置而言，所以一旦指针处于一个非法位置，没有参照物了，指针无论上移还是下移都是非法位</p>
</blockquote>
<p>reset()   :   初始化指针。<br>end()    :   将数组指针指向数组的最后一个元素。</p>
<blockquote>
<p>reset()和end()理解成相当于一个绝对路径的概念，我不需要管数组指针当前指向的位置，直接将数组指针指向第一个元素或者最后一个元素</p>
</blockquote>
<p>each()  :返回一个四个元素的数组，其中1和value代表当前数组指向的值，0和key指向当前数组的下标。并且他会让数组的指针下移一位</p>
<h5 id="while-each-list-遍历数组"><a href="#while-each-list-遍历数组" class="headerlink" title="while+each+list 遍历数组"></a>while+each+list 遍历数组</h5><p>each可以获取元素的值，下标和下移指针，所以直接和while配合，就可以遍历数组<br><strong>方法一</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">while($element = each($arr))&#123;</div><div class="line">	echo &apos;下标：&apos;,$element[0];</div><div class="line">	echo &apos;值：&apos;,$element[1];</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p><strong>方法二</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">while(list($key,$value)=each($arr))&#123;</div><div class="line">	echo &apos;下标：&apos;,$key;</div><div class="line">	echo &apos;值：&apos;,$value;</div><div class="line">&#125;</div></pre></td></tr></table></figure>
<p>list（）    ：  list可以将数组里面的值赋值给一个变量</p>
<blockquote>
<p>each获取的是一个数组类型的变量，所以可以利用list将数组的值获取出来</p>
<p>3种遍历数组的方式，for(),foreach(),while+each+list的方式，以后工作中90%的人基本上用的都是foreach,9%都会使用while+each+list的方法，for基本上没有人使用</p>
</blockquote>
<h3 id="关于赋值的指针问题"><a href="#关于赋值的指针问题" class="headerlink" title="关于赋值的指针问题"></a>关于赋值的指针问题</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div></pre></td><td class="code"><pre><div class="line">$arr=array(‘a’,’b’,’c’,’d’);</div><div class="line">$arr2=$arr;</div><div class="line">echo current($arr2);</div><div class="line">//结果是 a，地址传递</div></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">$arr=array(‘a’,’b’,’c’,’d’);</div><div class="line">next($arr);</div><div class="line">$arr2=$arr;</div><div class="line">echo current($arr2);</div><div class="line">// 结果是b，复制数组的时候，指针跟着一起被复制</div></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div></pre></td><td class="code"><pre><div class="line">$arr=array(&apos;a&apos;,&apos;b&apos;,&apos;c&apos;,&apos;d&apos;);</div><div class="line">$arr2=$arr;</div><div class="line">next($arr);</div><div class="line">echo current($arr2);</div><div class="line">// 结果是a ,复制数组以后，修改一个数组的指针，另一个数组不会一起发生变化。</div></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">$arr=array(&apos;a&apos;,&apos;b&apos;,&apos;c&apos;,&apos;d&apos;);</div><div class="line">next($arr);</div><div class="line">next($arr);</div><div class="line">next($arr);</div><div class="line">next($arr);</div><div class="line">$arr2=$arr;</div><div class="line">echo current($arr2);</div><div class="line">// 结果是a ,当一个数组处于一个非法位置的时候，复制给另一个数组，此时先查看哪个，哪个就会被初始化，另一个就不会初始化；</div></pre></td></tr></table></figure>
<h3 id="COW-写时复制"><a href="#COW-写时复制" class="headerlink" title="COW 写时复制"></a>COW 写时复制</h3><p>如果将一个变量赋值给另一个变量，不会立刻去开辟一个空间，只有当变量进行写操作的时候，才会给他开辟一个空间。</p>
<p>memory_get_usage()    获取文件占用空间的大小。<br>array_fill（开始下标，添加元素的数量，默认值）<br>shuffle() - 将数组打乱<br>array_fill() - 用给定的值填充数组</p>
<p>在foreach里面对原数组进行写操作时，复制的数组才开辟了一块空间</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div></pre></td><td class="code"><pre><div class="line">	header(&quot;content-type:text/html;charset=utf-8&quot;);</div><div class="line">	$arr=array(&apos;可乐&apos;,&apos;雪碧&apos;,&apos;王老吉&apos;);</div><div class="line">	foreach($arr as $key =&gt; $value)&#123;</div><div class="line">	&#125;</div><div class="line">	var_dump(current($arr));</div><div class="line">//指针停留在非法位，没有进行写操作。</div></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div></pre></td><td class="code"><pre><div class="line">	header(&quot;content-type:text/html;charset=utf-8&quot;);</div><div class="line">	$arr=array(&apos;可乐&apos;,&apos;雪碧&apos;,&apos;王老吉&apos;);</div><div class="line">	foreach($arr as $key =&gt; $value)&#123;</div><div class="line">		$arr[1]=&apos;加多宝&apos;;</div><div class="line">	&#125;</div><div class="line">	var_dump(current($arr));</div><div class="line">//结果为加多宝，foreach循环的是复制的原始数组，里面更改的也是原始数组。</div></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line">	header(&quot;content-type:text/html;charset=utf-8&quot;);</div><div class="line">	$arr=array(&apos;可乐&apos;,&apos;雪碧&apos;,&apos;王老吉&apos;);</div><div class="line">	foreach($arr as $key =&gt; $value)&#123;</div><div class="line">		if($key==1)&#123;</div><div class="line">			$arr[1]=&apos;加多宝&apos;;</div><div class="line">		&#125;</div><div class="line">	&#125;</div><div class="line">	var_dump(current($arr));</div><div class="line">//结果为王老吉，进行了写操作。</div></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">	$arr=array(&apos;可乐&apos;,&apos;雪碧&apos;,&apos;王老吉&apos;);</div><div class="line">	foreach($arr as $key =&gt; $value)&#123;</div><div class="line">		if($key==2)&#123;</div><div class="line">			$arr[1]=&apos;加多宝&apos;;</div><div class="line">		&#125;</div><div class="line">	&#125;</div><div class="line">	var_dump(current($arr));</div><div class="line">//结果为可乐，复制数组的时候，指针处于一个非法位置，所以指针被初始化操作了。</div></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div><div class="line">9</div></pre></td><td class="code"><pre><div class="line">	header(&quot;content-type:text/html;charset=utf-8&quot;);</div><div class="line">	$arr=array(&apos;可乐&apos;,&apos;雪碧&apos;,&apos;王老吉&apos;);</div><div class="line">	foreach($arr as $key =&gt; $value)&#123;</div><div class="line">		if($key==3)&#123;</div><div class="line">			$arr[1]=&apos;加多宝&apos;;</div><div class="line">		&#125;</div><div class="line">	&#125;</div><div class="line">	var_dump(current($arr));</div><div class="line">//if语句一直没有被执行，所以一直没有进行写时复制。所以遍历完数组以后，指针指向非法位</div></pre></td></tr></table></figure>
<p><strong>foreach变量数组总结</strong></p>
<blockquote>
<p>先复制后移动，原始数组保持指针不变<br>先移动后复制，复制的数组会将指针也复制了<br>指针处于非法位置时，进行复制，先查看哪个数组，哪个就先被初始化</p>
</blockquote>
<h3 id="关于数组的几个函数"><a href="#关于数组的几个函数" class="headerlink" title="关于数组的几个函数"></a>关于数组的几个函数</h3><p><strong>range（初始值，结束值）</strong><br><code>$arr = range(1,10);</code></p>
<p><strong>array_merge(数组1,数组2)</strong><br><code>$arr = array_merge(range(0,9),range(&#39;a&#39;,&#39;z&#39;));</code></p>
<blockquote>
<p>array_merge如果合并两个数字下标的数组，会将数字重新从0进行组合。<br>array_merge如果合并两个字符串下标的数组，后面的值会将前面的值覆盖。<br>array_merge合并两个数组，先从第一个数组开始合并，然后在合并第二个数组。</p>
</blockquote>
<p><strong>array_rand(数组，个数);</strong><br>随机获取一个数组的下标</p>
<blockquote>
<p>array_rand获取的是元素的下标，如果只获取一个元素下标，则是以普通数据类型进行存储，如果获取多个下标，则以数组的模式进行存储。<br>虽然array_rand是随机获取下标的，但是他获取多个下标的时候会从小到大排序</p>
</blockquote>
<p><strong>shuffle()</strong><br>可以打乱一个数组的元素</p>
<blockquote>
<p>返回值是bool(true),</p>
</blockquote>
<p><strong>随机验证码</strong></p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><div class="line">1</div><div class="line">2</div><div class="line">3</div><div class="line">4</div><div class="line">5</div><div class="line">6</div><div class="line">7</div><div class="line">8</div></pre></td><td class="code"><pre><div class="line">$arr = array_merge(range(0,9),range(&apos;a&apos;,&apos;z&apos;),range(&apos;A&apos;,&apos;Z&apos;));</div><div class="line">$arr2 = array_rand($arr,4);</div><div class="line">shuffle($arr2);</div><div class="line">$str = &apos;&apos;;</div><div class="line">foreach ($arr2 as $value) &#123;</div><div class="line">	$str.=$arr[$value];</div><div class="line">&#125;</div><div class="line">var_dump($str);</div></pre></td></tr></table></figure>
<p>补充：</p>
<blockquote>
<p>memory_get_usage() 获取当前文件占用空间的大小；<br>array_fill(0,10,’uiste’); 0开始下标，10是元素个数，uiste是每个元素的内容</p>
</blockquote>

          
        
      
    </div>

    <div>
      
    </div>

    <div>
      
    </div>

    <footer class="post-footer">
      

      

      
      
        <div class="post-eof"></div>
      
    </footer>
  </article>


    
  </section>

  
  <nav class="pagination">
    <a class="extend prev" rel="prev" href="/page/8/"><i class="fa fa-angle-left"></i></a><a class="page-number" href="/">1</a><span class="space">&hellip;</span><a class="page-number" href="/page/8/">8</a><span class="page-number current">9</span><a class="page-number" href="/page/10/">10</a><span class="space">&hellip;</span><a class="page-number" href="/page/14/">14</a><a class="extend next" rel="next" href="/page/10/"><i class="fa fa-angle-right"></i></a>
  </nav>



          </div>
          


          

        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      

      <section class="site-overview sidebar-panel  sidebar-panel-active ">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/images/avatar.png"
               alt="uiste" />
          <p class="site-author-name" itemprop="name">uiste</p>
          <p class="site-description motion-element" itemprop="description">Stay Hungry，Stay Foolish</p>
        </div>
        <nav class="site-state motion-element">
          <div class="site-state-item site-state-posts">
            <a href="/archives">
              <span class="site-state-item-count">70</span>
              <span class="site-state-item-name">日志</span>
            </a>
          </div>

          
            <div class="site-state-item site-state-categories">
              
                <span class="site-state-item-count">13</span>
                <span class="site-state-item-name">分类</span>
              
            </div>
          

          
            <div class="site-state-item site-state-tags">
              <a href="/tags">
                <span class="site-state-item-count">55</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        
          <div class="feed-link motion-element">
            <a href="/atom.xml" rel="alternate">
              <i class="fa fa-rss"></i>
              RSS
            </a>
          </div>
        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/uiste" target="_blank" rel="external nofollow" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://weibo.com/uiste" target="_blank" rel="external nofollow" title="微博">
                  
                    <i class="fa fa-fw fa-globe"></i>
                  
                  微博
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="http://www.zhihu.com/people/uiste" target="_blank" rel="external nofollow" title="知乎">
                  
                    <i class="fa fa-fw fa-globe"></i>
                  
                  知乎
                </a>
              </span>
            
          
        </div>

        
        

        
        
          <div class="links-of-blogroll motion-element links-of-blogroll-inline">
            <div class="links-of-blogroll-title">
              <i class="fa  fa-fw fa-globe"></i>
              友情链接
            </div>
            <ul class="links-of-blogroll-list">
              
                <li class="links-of-blogroll-item">
                  <a href="http://www.uiste.com" title="uiste 个人博客" target="_blank">uiste 个人博客</a>
                </li>
              
                <li class="links-of-blogroll-item">
                  <a href="http://uiste.github.io" title="uiste 技术博客" target="_blank">uiste 技术博客</a>
                </li>
              
            </ul>
          </div>
        

      </section>

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy;  2015 - 
  <span itemprop="copyrightYear">2016</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">uiste</span>
</div>

<div class="powered-by">
  由 <a class="theme-link" href="http://hexo.io" rel="external nofollow">Hexo</a> 趋势动力
</div>
<!--站长统计-->
<script src="https://s95.cnzz.com/z_stat.php?id=1259894121&web_id=1259894121" language="JavaScript"></script>
<!--<div class="theme-info">
  Theme -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next" rel="external nofollow">
    NexT.Mist
  </a>
</div> -->
&nbsp;&nbsp;&nbsp;本站总点击 <span id="busuanzi_value_site_pv"></span> 次
&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;您是第 <span id="busuanzi_value_site_uv"></span> 位访客

<script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js">
</script>

<script>
(function(){
    var bp = document.createElement('script');
    bp.src = '//push.zhanzhang.baidu.com/push.js';
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


        

        
      </div>
    </footer>

    <div class="back-to-top">
      <i class="fa fa-arrow-up"></i>
    </div>
  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  



  
  <script type="text/javascript" src="/vendors/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/vendors/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/vendors/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/vendors/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.0.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.0.1"></script>



  
  

  

  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.0.1"></script>



  

  
    
  

  <script type="text/javascript">
    var duoshuoQuery = {short_name:"uiste"};
    (function() {
      var ds = document.createElement('script');
      ds.type = 'text/javascript';ds.async = true;
      ds.id = 'duoshuo-script';
      ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
      ds.charset = 'UTF-8';
      (document.getElementsByTagName('head')[0]
      || document.getElementsByTagName('body')[0]).appendChild(ds);
    })();
  </script>

  
    
    <script src="/vendors/ua-parser-js/dist/ua-parser.min.js?v=0.7.9"></script>
    <script src="/js/src/hook-duoshuo.js"></script>
  






  
  
  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length == 0) {
       search_path = "search.xml";
    }
    var path = "/" + search_path;
    // monitor main search box;

    function proceedsearch() {
      $("body").append('<div class="popoverlay">').css('overflow', 'hidden');
      $('.popup').toggle();

    }
    // search function;
    var searchFunc = function(path, search_id, content_id) {
    'use strict';
    $.ajax({
        url: path,
        dataType: "xml",
        async: true,
        success: function( xmlResponse ) {
            // get the contents from search data
            isfetched = true;
            $('.popup').detach().appendTo('.header-inner');
            var datas = $( "entry", xmlResponse ).map(function() {
                return {
                    title: $( "title", this ).text(),
                    content: $("content",this).text(),
                    url: $( "url" , this).text()
                };
            }).get();
            var $input = document.getElementById(search_id);
            var $resultContent = document.getElementById(content_id);
            $input.addEventListener('input', function(){
                var matchcounts = 0;
                var str='<ul class=\"search-result-list\">';
                var keywords = this.value.trim().toLowerCase().split(/[\s\-]+/);
                $resultContent.innerHTML = "";
                if (this.value.trim().length > 1) {
                // perform local searching
                datas.forEach(function(data) {
                    var isMatch = true;
                    var content_index = [];
                    var data_title = data.title.trim().toLowerCase();
                    var data_content = data.content.trim().replace(/<[^>]+>/g,"").toLowerCase();
                    var data_url = data.url;
                    var index_title = -1;
                    var index_content = -1;
                    var first_occur = -1;
                    // only match artiles with not empty titles and contents
                    if(data_title != '' && data_content != '') {
                        keywords.forEach(function(keyword, i) {
                            index_title = data_title.indexOf(keyword);
                            index_content = data_content.indexOf(keyword);
                            if( index_title < 0 && index_content < 0 ){
                                isMatch = false;
                            } else {
                                if (index_content < 0) {
                                    index_content = 0;
                                }
                                if (i == 0) {
                                    first_occur = index_content;
                                }
                            }
                        });
                    }
                    // show search results
                    if (isMatch) {
                        matchcounts += 1;
                        str += "<li><a href='"+ data_url +"' class='search-result-title'>"+ data_title +"</a>";
                        var content = data.content.trim().replace(/<[^>]+>/g,"");
                        if (first_occur >= 0) {
                            // cut out 100 characters
                            var start = first_occur - 20;
                            var end = first_occur + 80;
                            if(start < 0){
                                start = 0;
                            }
                            if(start == 0){
                                end = 50;
                            }
                            if(end > content.length){
                                end = content.length;
                            }
                            var match_content = content.substring(start, end);
                            // highlight all keywords
                            keywords.forEach(function(keyword){
                                var regS = new RegExp(keyword, "gi");
                                match_content = match_content.replace(regS, "<b class=\"search-keyword\">"+keyword+"</b>");
                            });

                            str += "<p class=\"search-result\">" + match_content +"...</p>"
                        }
                        str += "</li>";
                    }
                })};
                str += "</ul>";
                if (matchcounts == 0) { str = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>' }
                if (keywords == "") { str = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>' }
                $resultContent.innerHTML = str;
            });
            proceedsearch();
        }
    });}

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched == false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };

    });

    $('.popup-btn-close').click(function(e){
      $('.popup').hide();
      $(".popoverlay").remove();
      $('body').css('overflow', '');
    });
    $('.popup').click(function(e){
      e.stopPropagation();
    });
  </script>


  

  

  

</body>
</html>
